How to compute number of seconds since the beginning of this day?
Solution 1
You can use standard C API:
- Get current time with
time()
. - Convert it to
struct tm
withgmtime_r()
orlocaltime_r()
. - Set its
tm_sec
,tm_min
,tm_hour
to zero. - Convert it back to
time_t
withmktime()
. - 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, ×tamp) == 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(×tamp);
if (midnight == -1) {
return -1;
}
return difftime(now, midnight);
}
Failures in other answers:
-
Not accounting for a daylight savings time change between midnight and now:
Similar code, mod, struct tm math -
Lack error handling:
Similar code, mod, struct tm math -
Uses universal time (apparently OP wants local time):
mod, struct tm math -
Assumes
time_t
is an integer type of a count in seconds:
Similar code UB in printing, mod -
Fails when
int
is 16-bit due to multiplication overflow:
mod -
Does not use fractional seconds (when they exist):
Similar code, mod, struct tm math
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, 2022Comments
-
yves Baumes almost 2 years
I want to get the number of seconds since midnight.
Here is my first guess:
time_t current; time(¤t); struct tm dateDetails; ACE_OS::localtime_r(¤t, &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);