c++时间戳转年月日时分秒
时间戳转年月日时分秒是比较常用的功能,调用api localtime_s把时间戳转成tm结构体,就可以通过tm结构体中的成员得到对应的年月日时分秒,需要注意的就是tm结构体部分成员的值不是真实的值,需要做一些简单的转换。具体实现请参照下面的demo代码
实现代码demo
#include <iostream> #include <time.h> /** * 微软文档地址 * https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/localtime-s-localtime32-s-localtime64-s?view=msvc-170 */ class Time { public: Time() : tm_({ 0 }) { time_t nowtime = time(0); /** * 根据微软文档,localtime_s返回0才是成功的 * 建议详细阅读微软文档,文档地址见顶部 */ valid_ = (::localtime_s(&tm_, &nowtime) == 0); } Time(time_t time) : tm_({ 0 }) { /** * 根据微软文档,localtime_s返回0才是成功的 * 建议详细阅读微软文档,文档地址见顶部 */ valid_ = (::localtime_s(&tm_, &time) == 0); } ~Time() {} /** * 返回值true则有效,可以正常使用 */ bool Valid() { return valid_; } int GetYear() { /** * 根据微软文档,年份是从1900年开始计算的,所以需加上1900 * tm_year: 年份(本年减去1900) * 建议详细阅读微软文档,文档地址见顶部 */ return tm_.tm_year + 1900; } int GetMonth() { /** * 根据微软文档,月份是从0开始计算的 * tm_mon: 月份(0-11;1月=0) * 建议详细阅读微软文档,文档地址见顶部 */ return tm_.tm_mon + 1; } int GetDay() { return tm_.tm_mday; } int GetHour() { return tm_.tm_hour; } int GetMinute() { return tm_.tm_min; } int GetSecond() { return tm_.tm_sec; } private: bool valid_; tm tm_; }; int main() { Time time; if (!time.Valid()) return 1; printf("当前时间:%d年%d月%d日%d时%d分%d秒", time.GetYear(), time.GetMonth(), time.GetDay(), time.GetHour(), time.GetMinute(), time.GetSecond()); getchar(); return 0; }
demo结果展示