从标准时间转化为Unix时间戳

使用<ctime>

核心数据结构: tm, time_t

核心API:

time_t mktime(tm* __std_time__);

将特定字符串根据指定格式提取出时间格式数据并存入tm地址中: std::istringstream >> get_time(tm* __addr__, string format);

#include <bits/stdc++.h>
using namespace std;

int main() {
tm time_struct = {};
time_struct.tm_year = 2024 - 1900; // 始于1900
time_struct.tm_mon = 12 - 1; // 从0开始
time_struct.tm_mday = 18; // 天
time_struct.tm_hour = 8; // 时
time_struct.tm_min = 52; // 分
time_struct.tm_sec = 30; // 秒

// std::mktime将标准时间转化为Unix时间戳
// time_t mktime(tm* __std_time__);
time_t timestamp = mktime(&time_struct);
if (timestamp == -1) {
cout << "failed";
} else {
cout << timestamp << endl;
}

// 使用 std::istringstream >> get_time(tm* __addr, string format);
time_struct = {};
istringstream time_stream("2024-12-18T08-52-30");
time_stream >> get_time(&time_struct, "%Y-%m-%dT%H-%M-%S");
timestamp = mktime(&time_struct);
cout << timestamp << endl;
return 0;
}

输出

1734483150
1734483150

从Unix时间戳转化为标准时间

核心数据结构: tm, time_t

核心API:

转化时间戳为tm结构体指针tm* localtime(time_t* __stamp__); , tm* gmtime(time_t* __stamp);

根据tm结构体指针格式化输出时间: put_time(tm* __tms__, string __format__);

#include <bits/stdc++.h>
using namespace std;

int main() {
time_t timestamp = 1734483150;

// std::localtime 转化为本地时间(tm结构体指针)
// tm* localtime(time_t* __stamp__);
tm* lc_time = localtime(&timestamp);

// std::put_time 格式化输出
// put_time(tm* __tms__, string __format__);
auto local_time = put_time(lc_time, "%Y-%m-%dT%H-%M-%S");
cout << local_time << endl;

// std::gmtime 转化为UTC时间(tm结构体指针)
// tm* gmtime(time_t* __stamp);
tm* utc_tm = gmtime(&timestamp);
auto utc_time = put_time(utc_tm, "%Y-%m-%dT%H-%M-%S");
cout << utc_time << endl;
}

输出

2024-12-18T08-52-30
2024-12-18T00-52-30