2011-04-22 140 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