C++ 将纪元时间转换为“真实”日期/时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1692184/
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
Converting epoch time to "real" date/time
提问by Austin Hyde
What I want to do is convert an epoch time (seconds since midnight 1/1/1970) to "real" time (m/d/y h:m:s)
我想要做的是将纪元时间(自 1970 年 1 月 1 日午夜以来的秒数)转换为“真实”时间(m/d/yh:m:s)
So far, I have the following algorithm, which to me feels a bit ugly:
到目前为止,我有以下算法,对我来说感觉有点难看:
void DateTime::splitTicks(time_t time) {
seconds = time % 60;
time /= 60;
minutes = time % 60;
time /= 60;
hours = time % 24;
time /= 24;
year = DateTime::reduceDaysToYear(time);
month = DateTime::reduceDaysToMonths(time,year);
day = int(time);
}
int DateTime::reduceDaysToYear(time_t &days) {
int year;
for (year=1970;days>daysInYear(year);year++) {
days -= daysInYear(year);
}
return year;
}
int DateTime::reduceDaysToMonths(time_t &days,int year) {
int month;
for (month=0;days>daysInMonth(month,year);month++)
days -= daysInMonth(month,year);
return month;
}
you can assume that the members seconds
, minutes
, hours
, month
, day
, and year
all exist.
你可以假设成员seconds
,minutes
,hours
,month
,day
,和year
存在。
Using the for
loops to modify the original time feels a little off, and I was wondering if there is a "better" solution to this.
使用for
循环来修改原始时间感觉有点不对劲,我想知道是否有“更好”的解决方案。
采纳答案by rxin
Be careful about leap years in your daysInMonth function.
请注意 daysInMonth 函数中的闰年。
If you want very high performance, you can precompute the pair to get to month+year in one step, and then calculate the day/hour/min/sec.
如果你想要非常高的性能,你可以预先计算一对以一步得到月+年,然后计算天/小时/分钟/秒。
A good solution is the one in the gmtime source code:
一个很好的解决方案是gmtime 源代码中的一个:
/*
* gmtime - convert the calendar time into broken down time
*/
/* $Header: gmtime.c,v 1.4 91/04/22 13:20:27 ceriel Exp $ */
#include <time.h>
#include <limits.h>
#include "loc_time.h"
struct tm *
gmtime(register const time_t *timer)
{
static struct tm br_time;
register struct tm *timep = &br_time;
time_t time = *timer;
register unsigned long dayclock, dayno;
int year = EPOCH_YR;
dayclock = (unsigned long)time % SECS_DAY;
dayno = (unsigned long)time / SECS_DAY;
timep->tm_sec = dayclock % 60;
timep->tm_min = (dayclock % 3600) / 60;
timep->tm_hour = dayclock / 3600;
timep->tm_wday = (dayno + 4) % 7; /* day 0 was a thursday */
while (dayno >= YEARSIZE(year)) {
dayno -= YEARSIZE(year);
year++;
}
timep->tm_year = year - YEAR0;
timep->tm_yday = dayno;
timep->tm_mon = 0;
while (dayno >= _ytab[LEAPYEAR(year)][timep->tm_mon]) {
dayno -= _ytab[LEAPYEAR(year)][timep->tm_mon];
timep->tm_mon++;
}
timep->tm_mday = dayno + 1;
timep->tm_isdst = 0;
return timep;
}
回答by sdtom
The standard library provides functions for doing this. gmtime()
or localtime()
will convert a time_t
(seconds since the epoch, i.e.- Jan 1 1970 00:00:00) into a struct tm
. strftime()
can then be used to convert a struct tm
into a string (char*
) based on the format you specify.
标准库提供了执行此操作的函数。gmtime()
或localtime()
将 a time_t
(自纪元以来的秒数,即- Jan 1 1970 00:00:00) 转换为 a struct tm
。strftime()
然后可用于根据您指定的格式将 astruct tm
转换为字符串 ( char*
)。
see: http://www.cplusplus.com/reference/clibrary/ctime/
见:http: //www.cplusplus.com/reference/clibrary/ctime/
Date/time calculations can get tricky. You are much better off using an existing solution rather than trying to roll your own, unless you have a really good reason.
日期/时间计算可能会变得棘手。除非您有充分的理由,否则最好使用现有解决方案而不是尝试推出自己的解决方案。
回答by brkeyal
An easy way (though different than the format you wanted):
一种简单的方法(尽管与您想要的格式不同):
std::time_t result = std::time(nullptr);
std::cout << std::asctime(std::localtime(&result));
Output: Wed Sep 21 10:27:52 2011
输出:2011 年 9 月 21 日星期三 10:27:52
Notice that the returned result will be automatically concatenated with "\n".. you can remove it using:
请注意,返回的结果将自动与“\n”连接..您可以使用以下方法将其删除:
std::string::size_type i = res.find("\n");
if (i != std::string::npos)
res.erase(i, res.length());
Taken from: http://en.cppreference.com/w/cpp/chrono/c/time
回答by brkeyal
time_t t = unixTime;
cout << ctime(&t) << endl;
回答by eidolon
If your original time type is time_t, you have to use functions from time.h i.e. gmtime etc. to get portable code. The C/C++ standards do not specify internal format (or even exact type) for the time_t, so you cannot directly convert or manipulate time_t values.
如果您的原始时间类型是 time_t,您必须使用 time.h 中的函数,即 gmtime 等来获取可移植代码。C/C++ 标准没有为 time_t 指定内部格式(甚至确切类型),因此您不能直接转换或操作 time_t 值。
All that is known is that time_t is "arithmetic type", but results of arithmetic operations are not specified - you cannot even add/subtract reliably. In practice, many systems use integer type for time_t with internal format of seconds since epoch, but this is not enforced by standards.
所有已知的是 time_t 是“算术类型”,但未指定算术运算的结果 - 您甚至无法可靠地加/减。实际上,许多系统对 time_t 使用整数类型,内部格式为自纪元以来的秒数,但这不是标准强制执行的。
In short, use gmtime (and time.h functionality in general).
简而言之,使用 gmtime(以及一般的 time.h 功能)。