C转换char[]为时间戳;

C convert char[] to timestamp;

本文关键字:时间戳 转换 char      更新时间:2023-10-16

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

警告: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

试试这个:

char date[] = "2011-04-01";
date[4] = date[7] = '';
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 );