首页 > 解决方案 > 如何在 C++ 中使用 unix 时间格式化 time_t 中的时间/日期字符串

问题描述

我有一个time_t值,我需要从中提取年、月、dayOfMonth、hourOfDay、分钟和秒的值(作为整数)。如果可能的话,我想尽量减少对库的依赖,但如果有一个库函数,你可以合理地确定它总是可用的,那就没问题了。time_t 值应该已经针对时区进行了调整,所以不用担心。

由于在一个相当大的公司项目中工作并使用远程服务器构建应用程序,我实际上不知道我们使用的是哪个版本的 C++,但它很可能是 C++11(可能是 C++98,但我对此表示怀疑) ,而且几乎可以肯定不是 C++17)。

标签: c++time-t

解决方案


If you have a time_t (which is from <time.h>), you don't need any additional library. You can just use the tm struct and localtime function that are also in <time.h>:

#include <iostream>
#include <time.h>
int main() {
    time_t t;
    t = time(NULL); // or some other value
    tm *timeNow = localtime(&t);
    std::cout << "Year: " << timeNow->tm_year+1900 << std::endl;
    std::cout << "Month: " << timeNow->tm_mon << std::endl;
    std::cout << "Day: " << timeNow->tm_mday << std::endl;
    std::cout << "Hour: " << timeNow->tm_hour << std::endl;
    std::cout << "Minute: " << timeNow->tm_min << std::endl;
    std::cout << "Second: " << timeNow->tm_sec << std::endl;
}

推荐阅读