2011-04-22 79 views
1

我有char date [] =「2011-04-01」;它如何轉換爲C或C++中的時間戳?C將char []轉換爲時間戳;

+2

也許這個回答能幫助:http://stackoverflow.com/questions/1002542/how-to-convert-datetime-to-unix-timestamp-in-c – 2011-04-22 10:01:21

+0

你的標題說,C,你的問題說: C或C++,並且您只標記了C++。你用C編程還是用C++編程? – Puppy 2011-04-22 10:36:07

回答

3

試試這個:

char date[] = "2011-04-01"; 
date[4] = date[7] = '\0'; 
struct tm tmdate = {0}; 
tmdate.tm_year = atoi(&date[0]) - 1900; 
tmdate.tm_mon = atoi(&date[5]) - 1; 
tmdate.tm_mday = atoi(&date[8]); 
time_t t = mktime(&tmdate); 
+0

請注意,此解決方案假定「2011-04-01」是_local_日期,並且DST不會生效爲「tmdate.tm_mday == 0」。因此'time_t t'可能從午夜起1個小時。 – chux 2017-01-26 18:09:38

4

警告:strptimePOSIX - 功能(可能無法在操作系統 「視窗」 平臺可通過time.h中)。

#include <time.h> 

struct tm time; 
strptime("2011-04-01", "%Y-%m-%d", &time); 
time_t loctime = mktime(&time); // timestamp in current timezone 
time_t gmttime = timegm(&time); // timestamp in GMT 
+1

未完全初始化/分配「時間」可能是一個問題:「未指定...將更新結構的當前內容或覆蓋結構的所有內容」。建議'struct tm time = {0};'並使用'time-> isdst == -1;'。 – chux 2017-01-26 18:16:25