C++中UNIX时间戳与日期互转
- 使用
time.h
头文件 localtime
可以把时间戳转为tm
结构体, tm结构体中可以格式化输出时间mktime
可以把tm结构体转为时间戳tm
结构体中:year
需要+1900,tm_mon
的范围是0-11,tm_mday
的范围是1-31
struct tm { int tm_sec; // seconds after the minute - [0, 60] including leap second int tm_min; // minutes after the hour - [0, 59] int tm_hour; // hours since midnight - [0, 23] int tm_mday; // day of the month - [1, 31] int tm_mon; // months since January - [0, 11] int tm_year; // years since 1900 int tm_wday; // days since Sunday - [0, 6] int tm_yday; // days since January 1 - [0, 365] int tm_isdst; // daylight savings time flag };
- 示例代码
#define _CRT_SECURE_NO_WARNINGS #include <string> #include <time.h> #include <iostream> using namespace std; void int_to_time(long long int u) { tm* lt = localtime(&u); printf("%d-%02d-%02d %02d:%02d:%02d\n", lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec); } tm* build_string_line(string s) { int year, month, day, hh, mm, ss; int _e = sscanf(s.c_str(), "%d-%d-%d %d:%d:%d", &year, &month, &day, &hh, &mm, &ss); tm* lt = new tm(); lt->tm_year = year - 1900; lt->tm_mon = month - 1; lt->tm_mday = day; lt->tm_hour = hh; lt->tm_min = mm; lt->tm_sec = ss; return lt; } void time_to_int(tm* lt) { //printf("%d-%02d-%02d %02d:%02d:%02d\n", lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec); long long int u2 = mktime(lt); printf("%lld\n", u2); }
tm* build_string_line(string s)
{
int year, month, day, hh, mm, ss;
int _e = sscanf(s.c_str(), "%d-%d-%d %d:%d:%d", &year, &month, &day, &hh, &mm, &ss);
tm* lt = new tm();
lt->tm_year = year - 1900;
lt->tm_mon = month - 1;
lt->tm_mday = day;
lt->tm_hour = hh;
lt->tm_min = mm;
lt->tm_sec = ss;
return lt;
}
void time_to_int(tm* lt)
{
//printf("%d-%02d-%02d %02d:%02d:%02d\n", lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec);
long long int u2 = mktime(lt);
printf("%lld\n", u2);
}
标签:-%,02d,int,lt,C++,UNIX,tm,year,互转 From: https://www.cnblogs.com/JiangOil/p/18050058