C++ UnixTime 到可读日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13536886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:26:34  来源:igfitidea点击:

UnixTime to readable date

c++datetimeunix-timestamp

提问by SuperUser

What is the best way to convert UnixTime to a date?

将 UnixTime 转换为日期的最佳方法是什么?

Is there a function for it or an algorithm?

有它的函数或算法吗?

回答by Olaf Dietsche

Unix time is seconds since epoch (1970-01-01). Depending on what you mean, you can convert it to a struct tmwith localtimeor convert it to a string with strftime.

Unix 时间是自纪元 (1970-01-01) 以来的秒数。根据您的意思,您可以struct tm使用localtime将其转换为 a 或使用strftime将其转换为字符串。

time_t t = time(NULL);
struct tm *tm = localtime(&t);
char date[20];
strftime(date, sizeof(date), "%Y-%m-%d", tm);


As the manual to localtime states

正如本地时间手册所述

The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.

返回值指向一个静态分配的结构,该结构可能会被对任何日期和时间函数的后续调用覆盖。

This is what some refer to as data races. This happens when two or more threads call localtimesimultaneously.

这就是一些人所说的数据竞争。当两个或多个线程localtime同时调用时会发生这种情况。

To protect from this, some suggest using localtime_s, which is a Microsoft only function. On POSIX systems, you should use localtime_rinstead

为了避免这种情况,有些人建议使用localtime_s,这是 Microsoft 独有的功能。在POSIX系统,你应该使用localtime_r,而不是

The localtime_r() function does the same, but stores the data in a user-supplied struct.

localtime_r() 函数执行相同的操作,但将数据存储在用户提供的结构中。

Usage would look like

用法看起来像

time_t t = time(NULL);
struct tm res;
localtime_r(&t, &res);

回答by melpomene

I'm going to assume you have the time in a time_t. First you need to convert that to a struct tm. You can do this with localtimeor gmtime, depending on whether you want to use the local timezone or GMT.

我假设你有时间在time_t. 首先,您需要将其转换为struct tm. 您可以使用localtime或执行此操作gmtime,具体取决于您要使用本地时区还是 GMT。

Then you can format that struct tmas a string with strftime. For example, to get a date like 2012-11-24you'd use the format "%Y-%m-%d".

然后您可以将其格式化struct tm为带有strftime. 例如,要像2012-11-24使用格式一样获取日期"%Y-%m-%d"

回答by Michael Haephrati

See also Convert Unix/Linux time to Windows FILETIME

另请参阅将 Unix/Linux 时间转换为 Windows FILETIME

This function should convert from UnixTime into Windows SYSTEMTIME

此函数应从 UnixTime 转换为 Windows SYSTEMTIME

SYSTEMTIME intChromeTimeToSysTime(long long int UnixTime)
{
    ULARGE_INTEGER uLarge;
    uLarge.QuadPart = UnixTime;
    FILETIME ftTime;
    ftTime.dwHighDateTime = uLarge.HighPart;
    ftTime.dwLowDateTime = uLarge.LowPart;
    SYSTEMTIME stTime;
    FileTimeToSystemTime(&ftTime, &stTime);
    return stTime;

}