将字符串时间转换为秒

时间:2011-02-25 15:26:59

标签: c datetime

这是代码,其中我将字符串时间转换为时间格式和时间转换为秒,但它显示一些奇怪的值。请帮助我

代码:

struct tm tm;
time_t t;
char s[25]="Sat Feb 19 12:53:39 2011";
if (strptime(s, "%A %b %d %H:%M:%S %Y", &tm) != NULL)


printf("year: %d; month: %d; day: %d;\n", tm.tm_year, tm.tm_mon, tm.tm_mday);
printf("hour: %d; minute: %d; second: %d\n",  tm.tm_hour, tm.tm_min, tm.tm_sec);
printf("week day: %d; year day: %d\n", tm.tm_wday, tm.tm_yday);

tm.tm_isdst = -1;      
t = mktime(&tm);
printf("seconds since the Epoch: %ld\n", (long) t);

out put是

  

年:111;月:1;日:19;

     

小时:12;分钟:53;第二:40

     

周日:6;年份:49

     自纪元以来

秒:1298102020

5 个答案:

答案 0 :(得分:2)

来自http://en.wikipedia.org/wiki/Time.h

C标准库中的日历时间(也称为“故障时间”)表示为struct tm结构,由以下成员组成:

Member  Description
int tm_hour hour (0 – 23)
int tm_isdst    Daylight saving time enabled (> 0), disabled (= 0), or unknown (< 0)
int tm_mday day of the month (1 – 31)
int tm_min  minutes (0 – 59)
int tm_mon  month (0 – 11, 0 = January)
int tm_sec  seconds (0 – 60, 60 = Leap second)
int tm_wday day of the week (0 – 6, 0 = Sunday)
int tm_yday day of the year (0 – 365)
int tm_year year since 1900

即您需要在年份中添加1900,而月份从零开始。

答案 1 :(得分:1)

您必须将1900添加到tm.tm_year。

答案 2 :(得分:0)

tm.tm_year是自1900年以来的年份数。而第0个月是1月。只需根据需要进行调整。

答案 3 :(得分:0)

输出正确。 struct tm将时间存储如下:

Member         Meaning            Range 
tm_sec   seconds after the minute  0-61* 
tm_min   minutes after the hour    0-59 
tm_hour  hours since midnight      0-23 
tm_mday  day of the month          1-31 
tm_mon   months since January      0-11 
tm_year  years since 1900  
tm_wday  days since Sunday         0-6 
tm_yday  days since January 1      0-365 
tm_isdst Daylight Saving Time flag 

Source

答案 4 :(得分:0)

struct tm tm;
time_t t;
char s[25]="Sat Feb 19 12:53:39 2011";
if (strptime(s, "%A %b %d %H:%M:%S %Y", &tm) != NULL)

/* Don't do: tm.tm_year += 1900; 
   before computing the Epoch or you'll break it! 
*/

printf("year: %d; month: %d; day: %d;\n", tm.tm_year + 1900, tm.tm_mon, tm.tm_mday);
printf("hour: %d; minute: %d; second: %d\n",  tm.tm_hour, tm.tm_min, tm.tm_sec);
printf("week day: %d; year day: %d\n", tm.tm_wday, tm.tm_yday);

tm.tm_isdst = -1;      
t = mktime(&tm);
printf("seconds since the Epoch: %ld\n", (long) t);