C将char []转换为时间戳;

时间:2011-04-22 09:58:56

标签: c++ timestamp char

我有char date [] =“2011-04-01”;它如何在C或C ++中转换为时间戳?

2 个答案:

答案 0 :(得分:4)

警告: strptime 是一个POSIX - 功能(可能无法在操作系统“Windows”平台上通过 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 :(得分: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 );