Cool Method for Milliseconds Since Midnight for C/C++

cplusplus.jpg

I was working with exchange data today, and realized that the "timestamp in microseconds since epoch" wasn't really a great timestamp, and, in fact, the exchanges are using the reference point of midnight, and only to milliseconds. The problem was, I didn't have a simple method that could give me the time with respect to midnight. I didn't see anything that was really helpful on google either.

Then it hit me... It was like a flash - like all great insights are: use the seconds in the response from gettimeofday() as the input to localtime_r() and then you have one time "instant" defined, but you can pick off the hours, minutes, and secons and then add in the milliseconds by dividing the microseconds.

Like this:

  uint32_t TransferStats::msecSinceMidnight()
  {
    /*
     * This is really interesting. I need to get the msec since midnight,
     * and the cleanest way I could think to do this was to get the
     * timeval struct and then take the tv_sec component of it and pass
     * it to localtime_r to get the hour, min, sec parts of the time and
     * then piece it all together again. Kinda slick.
     */
    // get the time now as the (sec + usec) since epoch
    struct timeval tv;
    gettimeofday(&tv, NULL);
    // now take the seconds component and get the current hour, min, sec
    struct tm   now;
    localtime_r(&tv.tv_sec, &now);
    // now let's calculate the time since midnight...
    return (tv.tv_usec/1000 + ((now.tm_hour * 60 + now.tm_min) * 60
                                + now.tm_sec) * 1000);
  }