从标准时间转化为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; time_struct.tm_mon = 12 - 1; time_struct.tm_mday = 18; time_struct.tm_hour = 8; time_struct.tm_min = 52; time_struct.tm_sec = 30;
time_t timestamp = mktime(&time_struct); if (timestamp == -1) { cout << "failed"; } else { cout << timestamp << endl; }
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; }
|
输出
从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;
tm* lc_time = localtime(×tamp); auto local_time = put_time(lc_time, "%Y-%m-%dT%H-%M-%S"); cout << local_time << endl;
tm* utc_tm = gmtime(×tamp); 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
|