title: How to get date and time string accurate to milliseconds in C++ in Linux?
body: <p>I want to be able to put into a string the local time and date with millisecond resolution like so:</p>
  
  <p>YYYY-MM-DD hh:mm:ss.sss</p>
  
  <p>Seems like a simple thing to do, but I haven't found a simple answer for how to do this.  I am writing in C++ and do have access to 11 compiler but am fine using a C solution if it's cleaner.  I found a post here with a solution <a href="https://stackoverflow.com/questions/39230127/get-both-date-and-time-in-milliseconds">Get both date and time in milliseconds</a> but surely it can't be that difficult given use of standard libraries.  I'm probably going to move forward with that type of solution but was hoping to add to the knowledge base by asking the question here on SO.</p>
  
  <p>I know this will work but again, seems unnecessarily difficult:</p>
  
  <pre><code>#include &lt;sys/time.h&gt;
  #include &lt;stdio.h&gt;
  
  int main(void)
  {
      string sTimestamp;
      char acTimestamp[256];
  
      struct timeval tv;
      struct tm *tm;
  
      gettimeofday(&amp;tv, NULL);
  
      tm = localtime(&amp;tv.tv_sec);
  
      sprintf(acTimestamp, "%04d-%02d-%02d %02d:%02d:%02d.%03d\n",
              tm-&gt;tm_year + 1900,
              tm-&gt;tm_mon + 1,
              tm-&gt;tm_mday,
              tm-&gt;tm_hour,
              tm-&gt;tm_min,
              tm-&gt;tm_sec,
              (int) (tv.tv_usec / 1000)
          );
  
      sTimestamp = acTimestamp;
  
      cout &lt;&lt; sTimestamp &lt;&lt; endl;
  
      return 0;
  }
  </code></pre>
  
  <p>Tried looking at put_time for C++ and strftime for the old C way.  Both only allow me to get to second resolution best I can tell.  You can see the two approaches I've gotten so far below.  I would like to put it into a string</p>
  
  <pre><code>auto t = std::time(nullptr);
  auto tm = *std::localtime(&amp;t);
  std::cout &lt;&lt; std::put_time(&amp;tm, "%Y-%m-%d %H:%M:%S") &lt;&lt; std::endl;
  
  time_t rawtime;
  struct tm * timeinfo;
  char buffer[80];
  
  time (&amp;rawtime);
  timeinfo = localtime(&amp;rawtime);
  
  strftime(buffer,sizeof(buffer),"%Y-%m-%d %I:%M:%S",timeinfo);
  std::string str(buffer);
  
  std::cout &lt;&lt; str;
  </code></pre>
  
  <p>Only thing I can figure out is to use gettimeofday and get rid of all the data except the last second and append it to the timestamp, still wish there was a cleaner approach.</p>
  
  <p>Anyone find a solution that works better?</p>