Reputation: 408
How can I get the number of seconds passed since January 1, 1970 for a specific date, for example:"2017-09-14 23:24:46"
#include <stdio.h>
#include <stdint.h>
#include <time.h>
int main()
{
struct tm tmVar;
time_t timeVar;
sscanf("2017-09-14 23:24:46","%d-%d-%d %d:%d:%d",&tmVar.tm_year
,&tmVar.tm_mon, &tmVar.tm_mday,
&tmVar.tm_hour, &tmVar.tm_min,
&tmVar.tm_sec);
tmVar.tm_isdst = 1;
printf("tm_year :%d\n",tmVar.tm_year);
printf("tm_month :%d\n",tmVar.tm_mon);
printf("tm_day :%d\n",tmVar.tm_mday);
printf("tm_hour :%d\n",tmVar.tm_hour);
printf("tm_min :%d\n",tmVar.tm_min);
printf("tm_sec :%d\n",tmVar.tm_sec);
timeVar = mktime(&tmVar);
printf("time %d\n",timeVar);
}
The output however is not what I expect:
tm_year :2017
tm_month :9
tm_day :14
tm_hour :23
tm_min :24
tm_sec :46
time 1336625342
According to epochconverter.com, the proper value should be 1510529086. Why am I not getting this value?
Upvotes: 1
Views: 3257
Reputation: 223699
You need to adjust the values stored in your struct.
The tm_year
field is years since 1900, so subtract 1900 from this value.
The tm_mon
field is months since January, so subtract 1 from this value.
So do the following after populating the struct:
tmVar.tm_year -= 1900;
tmVar.tm_mon--;
Output:
tm_year :117
tm_month :8
tm_day :14
tm_hour :23
tm_min :24
tm_sec :46
time 1505445886
Upvotes: 3