Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: how to get the actual time with time and localtime?
    text
    copied!<p>I'm looking for a way to save the time in a HH::MM::SS fashion in C++. I saw here that they are many solutions and after a little research I opted for <code>time</code> and <code>localtime</code>. However, it seems like the <code>localtime</code> function is a little tricky, since it <a href="http://rabbit.eng.miami.edu/info/functions/time.html#localtime">says</a>: </p> <blockquote> <p>All calls to localtime and gmtime use the same static structure, so each call overwrites the results of the previous call.</p> </blockquote> <p>The problem that this causes is shown in the next snippet of code:</p> <pre><code>#include &lt;ctime&gt; #include &lt;iostream&gt; using namespace std; int main() { time_t t1 = time(0); // get time now struct tm * now = localtime( &amp; t1 ); std::cout &lt;&lt; t1 &lt;&lt; std::endl; sleep(2); time_t t2 = time(0); // get time now struct tm * now2 = localtime( &amp; t2 ); std::cout &lt;&lt; t2 &lt;&lt; std::endl; cout &lt;&lt; (now-&gt;tm_year + 1900) &lt;&lt; '-' &lt;&lt; (now-&gt;tm_mon + 1) &lt;&lt; '-' &lt;&lt; now-&gt;tm_mday &lt;&lt; ", " &lt;&lt; now-&gt;tm_hour &lt;&lt; ":" &lt;&lt; now-&gt;tm_min &lt;&lt; ":" &lt;&lt; now-&gt;tm_sec &lt;&lt; endl; cout &lt;&lt; (now2-&gt;tm_year + 1900) &lt;&lt; '-' &lt;&lt; (now2-&gt;tm_mon + 1) &lt;&lt; '-' &lt;&lt; now2-&gt;tm_mday &lt;&lt; ", " &lt;&lt; now2-&gt;tm_hour &lt;&lt; ":" &lt;&lt; now2-&gt;tm_min &lt;&lt; ":" &lt;&lt; now2-&gt;tm_sec &lt;&lt; endl; } </code></pre> <p>A typical output for this is: </p> <pre><code>1320655946 1320655948 2011-11-7, 9:52:28 2011-11-7, 9:52:28 </code></pre> <p>So as you can see, the <code>time_t</code> timestamps are correct, but the localtime messes everything up. </p> <p>My question is: how do I convert a timestamp ot type <code>time_t</code> into a human-readable time?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload