gpt4 book ai didi

c++ - 将从 "midnight 1904-1-1"开始的秒数转换为日期时间字符串

转载 作者:行者123 更新时间:2023-12-02 06:16:06 24 4
gpt4 key购买 nike

在某些多媒体元数据中,可能存在以秒为单位的日期时间UTC 时间 1904 年 1 月 1 日午夜。

据我所知,C/C++ 标准库中的日期时间函数通常基于 1970-1-1 午夜,至少在 Visual C++ 中,C/C++/Win32-API 中是否有函数来转换秒从“1904-1-1午夜”开始到日期时间字符串,例如“hh:mm:ss MM.dd, yyyy”或其他格式字符串或类似“struct tm”的结构?

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:

int main()
{
SYSTEMTIME systm;
memset(&systm, 0, sizeof(systm));

systm.wYear = 1904;
systm.wMonth = 1;
systm.wDay = 1;

FILETIME filetm;
if (SystemTimeToFileTime(&systm, &filetm) == FALSE){
printf("Failed to convert system time to file-time.\n");
return 0;
}

ULARGE_INTEGER nanoSeconds;
nanoSeconds.HighPart = filetm.dwHighDateTime;
nanoSeconds.LowPart = filetm.dwLowDateTime;

nanoSeconds.QuadPart += 3600ULL * 10000000; // add 1hour based on 1904/1/1 midnight

filetm.dwHighDateTime = nanoSeconds.HighPart;
filetm.dwLowDateTime = nanoSeconds.LowPart;

if (FileTimeToSystemTime(&filetm, &systm) == FALSE){
printf("Failed to convert file-time to system time.\n");
return 0;
}

printf("New system time by adding 1 hour: %d-%02d-%02d %02d:%02d:%02d.%03d\n",
systm.wYear, systm.wMonth, systm.wDay,
systm.wHour, systm.wMinute, systm.wSecond, systm.wMilliseconds);

return 0;
}

输出为

New system time by adding 1 hour: 1904-01-01 01:00:00.000

解决方案#2:

用@Howard Hinnant的date.h也可以解决这个问题,请看他提供的示例代码https://stackoverflow.com/a/49733937/3968307

最佳答案

这是使用 Howard Hinnant's free, open-source date/time library 的好时机:

#include "date/date.h"
#include <cstdint>
#include <iostream>
#include <string>

std::string
convert(std::int64_t seconds_since_1904)
{
using namespace date;
using namespace std::chrono;
constexpr auto offset = sys_days{January/1/1970} - sys_days{January/1/1904};
return format("%T %m.%d, %Y", sys_seconds{seconds{seconds_since_1904}} - offset);
}

int
main()
{
std::cout << convert(3'606'124'378) << '\n';
}

输出:

13:12:58 04.09, 2018

更新

以上代码将通过以下方式移植到 C++20(发布时):

  • 更改#include "date/date.h"#include <chrono>
  • 更改using namespace date;using namespace std;
  • 更改"%T %m.%d, %Y""{:%T %m.%d, %Y}"

关于c++ - 将从 "midnight 1904-1-1"开始的秒数转换为日期时间字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49731397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com