#include <stdio.h>
#include <time.h>
int main(){
printf("%d\n", time(NULL));
printf("Second: %ld\n", time(NULL)/60);
printf("Minute: %ld\n", time(NULL)/(60*60));
printf("Hour: %ld\n", time(NULL)/(60*60*60));
printf("Day %ld\n", time(NULL)/(60*60*60*24));
return 0;
}
Today is November 19. And it is 323. day of the year. When I run the program it print 321. What is the reason?
CodePudding user response:
time(NULL)
returns seconds since January 1:st 1970.
Your calculations are wrong in that you assume that they are from the beginning of current the year and you divide by seconds once too many.
Amazingly, the two errors almost take each other out and you end up with a result which is nearly, but not exactly right. In fact, had you been running this program two years ago (i.e. sixty years after 1970) you would have gotten the "right" result. In fact, if you would run it eight years from now (i.e. sixty years after 1970) you will get the "right" answer.
CodePudding user response:
Because your day calculation is off. Here is a way to get this right:
#include <stdio.h>
#include <time.h>
/* constants for time conversion
* source: https://www.epochconverter.com/
Human-readable time(Seconds)
1 Minute 60
1 hour 3,600
1 day 86,400
1 week 604,800
1 month (30.44 days) 2,629,743
1 year (365.24 days) 31,556,926
*/
int main(){
// number of years since epoch
// 00:00 January 1, 1970
time_t t = time(NULL) % 31556926; /* number of seconds elapsed in this year */
printf("Seconds: %ld\n", t);
printf("Minute: %ld\n", t/60);
printf("Hour: %ld\n", t/3600);
printf("Day %ld\n",t/86400);
return 0;
}