如何在C++中显示时间?今天蒟蒻来给大家谈一下C++中的ctime库。 首先,我们要了解一个概念—时间戳。 从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数,就是Unix时间戳。
#include<iostream>
#include<ctime>
int main()
{
std::time_t t=std::time(NULL);//获取时间戳
std::cout << "timestamp:" << t;//输出
return 0;
}找个编译器跑一遍就可以获得时间戳了。
不过这样没有用处,如果电子设备无法显示时间了,我们还要拿着草稿纸计算半天。
所以我们还要了解一个概念—格式化输出,可以输出年(%Y)月(%m)日(%d)时(%H)分(%M)秒(%S)
但是世界各地的时间不相同,想获取本地时间,还要使用localtime。
#include <iostream>
#include <ctime>
int main() {
std::time_t now = std::time(nullptr); //获取当前时间戳
std::tm* local_time = std::localtime(&now);//转为本地时间戳
if (local_time == nullptr) {
std::cerr << "error" << std::endl;
return 1;
}
char time_str[100];//用于存储
std::strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", local_time); //格式化
std::cout << "time:" << time_str << std::endl;//输出
return 0; //结束
}想更精确,需要使用C++11后的chrono库,但很麻烦,蒟蒻不会。
再见👋