How to calculate the number of seconds from the beginning of this day?

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); 
+4
source share
3 answers

You can use the standard C API:

  • Get the current time using time() .
  • Convert it to struct tm using gmtime_r() or localtime_r() .
  • Set tm_sec , tm_min , tm_hour to 0.
  • Convert it back to time_t with mktime() .
  • Find the difference between the original time_t 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; } 
+10
source

Also modulo the number of seconds per day is normal:

  return nbOfSecondsSince1970 % (24 * 60 * 60) 
+2
source

Here is another possible solution:

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

I think this is simpler, I tried the solution above and it did not work in VS2008.

PS: Sorry for my English.

EDIT: this will always output the same number, because it multiplies the number of hours - so if it is 2:00 AM it will always output 7200. Use instead:

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

Source: https://habr.com/ru/post/1303338/


All Articles