C++中UNIX時間戳與日期互轉

酱_油發表於2024-03-03

C++中UNIX時間戳與日期互轉

  1. 使用time.h標頭檔案
  2. localtime 可以把時間戳轉為 tm 結構體, tm結構體中可以格式化輸出時間
  3. mktime可以把tm結構體轉為時間戳
  4. 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
};
  1. 示例程式碼
#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);
}

相關文章