Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute number of seconds since the beginning of this day?

Tags:

c++

time

I want to get the number of seconds since midnight.

Here is my first guess:

  time_t current;
  time(&current);
  struct tm dateDetails;
  ACE_OS::localtime_r(&current, &dateDetails);

  // Get the current session start time
  const time_t yearToTime     = dateDetails.tm_year - 70; // year to 1900 converted into year to 1970
  const time_t ydayToTime     = dateDetails.tm_yday;
  const time_t midnightTime   = (yearToTime * 365 * 24 * 60 * 60) + (ydayToTime* 24 * 60 * 60);
  StartTime_                  = static_cast<long>(current - midnightTime);
like image 396
yves Baumes Avatar asked Mar 06 '10 13:03

yves Baumes


1 Answers

You can use standard C API:

  1. Get current time with time().
  2. Convert it to struct tm with gmtime_r() or localtime_r().
  3. Set its tm_sec, tm_min, tm_hour to zero.
  4. Convert it back to time_t with mktime().
  5. Find the difference between the original time_t value and the new one.

Example:

#include <time.h>
#include <stdio.h>

time_t
day_seconds() {
    time_t t1, t2;
    struct tm tms;
    time(&t1);
    localtime_r(&t1, &tms);
    tms.tm_hour = 0;
    tms.tm_min = 0;
    tms.tm_sec = 0;
    t2 = mktime(&tms);
    return t1 - t2;
}

int
main() {
    printf("seconds since the beginning of the day: %lu\n", day_seconds());
    return 0;
}
like image 158
Alex B Avatar answered Sep 27 '22 22:09

Alex B