一、获取当前 时间戳 (是指从某个特定的起始时间点到特定时间的秒数或毫秒数等时间单位的数值表示。)
std::time_t now = std::time(nullptr);
-
std::time_t 是一种用于表示时间的整数类型,通常以秒为单位,从一个特定的时间点(通常是1970年1月1日 00:00:00UTC)开始计数。
-
std::time(nullptr)函数返回当前时间的时间戳。它接受一个指向 std::time_t 类型的指针作为参数,这里传入 nullptr 表示不需要特定的时间存储位置,函数会返回当前时间值并存储在now 变量中。
二、将时间戳转换为本地时间结构体
std::tm* t = std::localtime(&now);
localtime(&now)是C和C++中用于将时间转换为本地时间的函数调用。
函数作用:localtime 函数将一个表示从特定时间点(通常是1970年1月1日00:00:00 UTC)到当前时间经过的秒数的时间戳(通常是通过time(NULL)或其他方式获得的 time t类型的值)转换为一个struct tm 结构体,该结构体表示的是本地时间的各个组成部分如年、月、日、小时、分钟、秒等。
-
std::localtime 函数接受一个指向 std::time_t类型的指针作关参数,这里是 &now ,即指向刚才获取的时间戳的地址。
-
该函数将时间戳转换为一个 struct tm 结构体,这个结构体表示本地时间的各个组成部分,包括年、月、日、小时、分钟、秒等
-
函数返回一个指向 struct tm 结构体的指针,存储在t变量中。如果转换失败,返回 nullptr。
三、解读 struct tm 结构体的成员
-
t->tm_year :表示从 1900 年开始的年份数。例如,如果当前是2024年,那么tm_year 的值为 124(2024-1900)
-
t->tm_mon :表示月份,取值范围是0到11,分别代表一月到十二月。所以需要加1才能得到人们习惯的月份表示(1到12)。
-
t->tm_mday :表示一个月中的日期,从1开始计数。
-
t->tm hour、t->tm sec :t->tm min分别表示小时、分钟、秒。
四、示例用法
#include <iostream>
#include <ctime>
int main() {
std::time_t now = std::time(nullptr);
std::tm* t = std::localtime(&now);
if (t!= nullptr) {
std::cout << "Year: " << t->tm_year + 1900 << std::endl;
std::cout << "Month: " << t->tm_mon + 1 << std::endl;
std::cout << "Day: " << t->tm_mday << std::endl;
std::cout << "Hour: " << t->tm_hour << std::endl;
std::cout << "Minute: " << t->tm_min << std::endl;
std::cout << "Second: " << t->tm_sec << std::endl;
} else {
std::cerr << "Failed to get local time." << std::endl;
}
return 0;
}