抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

字符串与时间戳的转换

日期字符串转换为时间戳

思路:

  1. 将日期字符串转换为时间结构体
  2. 将时间结构体转换为对应的时间戳(time_t类型,其实是long类型的别名)
日期字符串转换为时间戳
1
2
3
4
5
6
7
8
9
time_t convertDateToTimestamp(const string &date)
{
// 首先在后面添加时间
char dateTimeBuf[64];
snprintf(dateTimeBuf, sizeof(dateTimeBuf), "%s 00:00:00", date.c_str());
struct tm dateTM;
strptime(dateTimeBuf, "%Y-%m-%d %H:%M:%S", &dateTM);
return mktime(&dateTM);
}

日期时间字符串转换为时间戳

思路:

  1. 将日期字符串转换为时间结构体
  2. 将时间结构体转换为对应的时间戳(time_t类型,其实是long类型的别名)
日期时间字符串转换为时间戳
1
2
3
4
5
6
7
// 日期时间字符串转换为对应的时间戳
time_t convertDatetimeToTimestamp(const string &date_time)
{
struct tm dtTM;
strptime(date_time.c_str(), "%Y-%m-%d %H:%M:%S", &dtTM);
return mktime(&dtTM);
}

时间戳转换为日期字符串

思路:

  1. 将时间戳转换为struct tm类型的时间:使用localtime_r函数或者localtime函数
  2. 然后将struct tm类型的时间按照给定格式化串格式化为字符串:使用strftime函数
时间戳转换为日期字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 时间戳转换为日期
void convertTimestampToDate(time_t timestamp, string &date)
{
// 1. 将时间戳转换为struct tm类型:
// localtime是不可重入函数,非线程安全,但是localtime_r是可重入函数,线程安全的
struct tm dateTm;
localtime_r(&timestamp, &dateTm);
printf("%d-%d-%d\n", dateTm.tm_year + 1900, dateTm.tm_mon + 1,
dateTm.tm_mday);
// 2. 将struct tm类型转换为自定义格式化字符串
char dateBuf[16];
strftime(dateBuf, sizeof(dateBuf), "%Y-%m-%d", &dateTm);
date = dateBuf;
}

时间戳转换为日期时间字符串

思路:

  1. 将时间戳转换为struct tm类型的时间:使用localtime_r函数或者localtime函数
  2. 然后将struct tm类型的时间按照给定格式化串格式化为字符串:使用strftime函数
时间戳转换为日期时间字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
// 时间戳转换为日期时间
void convertTimestampToDatetime(time_t timestamp, string &date_time)
{
// 1. 将时间戳转换为struct tm类型:
// localtime是不可重入函数,非线程安全,但是localtime_r是可重入函数,线程安全的
struct tm dateTimeTm;
localtime_r(&timestamp, &dateTimeTm);
// 2. 将struct tm类型转换为自定义格式化字符串
char dateTimeBuf[32];
strftime(dateTimeBuf, sizeof(dateTimeBuf), "%Y-%m-%d %H:%M:%S",
&dateTimeTm);
date_time = dateTimeBuf;
}