2013-10-23 28 views
0

我不明白,爲什麼這不起作用? PS:我發現這段代碼來自一些谷歌!strtoul將字符串日期(「2013年3月10日14時01分00秒」)轉換爲time_t

問題:我不知道它爲什麼會起作用?這是否考慮時區?!

1 #include<stdio.h> 
    2 #include <stdlib.h> 
    3 #include <string> 
    4 #include <time.h> 
    5 int main() 
    6 { 
    7  std::string text("10/10/2013 14:01:00"); 
    8  const char* nptr = text.c_str(); 
    9  char* endptr = NULL; 
10  time_t seconds_from_epoch = strtoul(nptr, &endptr, 0); 
11  if (secs != 0) 
12   printf("Secs: %ld\n", secs); 
13  if (*nptr != '\0' && endptr && *endptr == '\0') { 
14   printf("Secs: %ld\n", secs); 
15  } else { 
16   printf("Unable to convert\n"); 
17  } 
18 } 

回答

0

這是錯誤的假設。

這是我如何做:

21  printf("************************\n"); 
22  int day, month, yr, hr, min, sec, tzone; 
23  char* more = (char *)nptr; 
24  month = strtol(more, &more, 10); 
25  day = strtol(more+1, &more, 10); 
26  yr = strtol(more+1, &more, 10); 
27  hr = strtol(more+1, &more, 10); 
28  min = strtol(more+1, &more, 10); 
29  sec = strtol(more+1, &more, 10); 
30  tzone = strtol(more+1, &more, 10); 
31 
32  printf("Month: %d, Day: %d, Year: %d, Hour: %d, Min: %d, Sec: %d, Tzone:  %d\n", 
33    month, day, yr, hr, min, sec, tzone); 

然後可以使用結構TM和mktime。

+0

strptime是你的朋友。 – Petesh

+0

對,我希望可以直接轉換爲time_t或tm的inbuild。無論如何,它的工作! –

相關問題