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

11,179

Solution 1

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;
}

Solution 2

Also a modulo to the number of seconds in a day is ok:

 return nbOfSecondsSince1970 % (24 * 60 * 60)

Solution 3

Here is another possible solution:

time_t stamp=time(NULL);
struct tm* diferencia=localtime(&stamp);
cout << ((diferencia->tm_hour*3600)+(diferencia->tm_min*60)+(diferencia->tm_sec));

Solution 4

Even after 11 years, some improvements:

  • Improved DST handling

  • Error checking

  • Proper time_t subtraction

Code:

#include <ctime>

// Error: return -1
// Success: return [0 ... 90,000) (not 86,400 due to DST)
double seconds_since_local_midnight() {
  time_t now;
  if (time(&now) == -1) {
    return -1;
  }
  struct tm timestamp;
  if (localtime_r(&now, &timestamp) == 0) { // C23
    return -1;
  }
  timestamp.tm_isdst = -1; // Important
  timestamp.tm_hour = 0;
  timestamp.tm_min = 0;
  timestamp.tm_sec = 0;
  time_t midnight = mktime(&timestamp);
  if (midnight == -1) {
    return -1;
  }
  return difftime(now, midnight);
}

Failures in other answers:

Share:
11,179
yves Baumes
Author by

yves Baumes

C++ developper. Keen on learning many things. Particularly on concurrency, multithreading, etc. And I'd like to improve my english !

Updated on June 17, 2022

Comments

  • yves Baumes
    yves Baumes almost 2 years

    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);