从1970年1月1日00:00开始,我有以纳秒为单位的int64秒数,我正在尝试将其转换为月/日/年/星期几。
迭代地做这件事很容易,我已经做到了,但我想用公式化的方式来做。我要找的是真正的数学。
发布于 2014-06-13 06:35:57
这段代码可以工作..。
用法: uint32_t getSecsSinceEpoch(1970,月,日,years_since_epoch,时,分,秒);
示例: timestamp = getSecsSinceEpoch(1970,6,12,(2014 - 1970),15,29,0)
回报率: 1402586940
你可以在www.epochconverter.com上验证。
写这篇文章花了大约20分钟,其中大部分时间都花在和一个朋友争论我是否应该包含leap-seconds,nano-seconds等等。
玩得开心..。
布莱恩·威尔卡特博士
#define DAYSPERWEEK (7)
#define DAYSPERNORMYEAR (365U)
#define DAYSPERLEAPYEAR (366U)
#define SECSPERDAY (86400UL) /* == ( 24 * 60 * 60) */
#define SECSPERHOUR (3600UL) /* == ( 60 * 60) */
#define SECSPERMIN (60UL) /* == ( 60) */
#define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400)))
const int _ytab[2][12] = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
/****************************************************
* Class:Function : getSecsSomceEpoch
* Input : uint16_t epoch date (ie, 1970)
* Input : uint8 ptr to returned month
* Input : uint8 ptr to returned day
* Input : uint8 ptr to returned years since Epoch
* Input : uint8 ptr to returned hour
* Input : uint8 ptr to returned minute
* Input : uint8 ptr to returned seconds
* Output : uint32_t Seconds between Epoch year and timestamp
* Behavior :
*
* Converts MM/DD/YY HH:MM:SS to actual seconds since epoch.
* Epoch year is assumed at Jan 1, 00:00:01am.
****************************************************/
uint32_t getSecsSinceEpoch(uint16_t epoch, uint8_t month, uint8_t day, uint8_t years, uint8_t hour, uint8_t minute, uint8_t second)
{
unsigned long secs = 0;
int countleap = 0;
int i;
int dayspermonth;
secs = years * (SECSPERDAY * 365);
for (i = 0; i < (years - 1); i++)
{
if (LEAPYEAR((epoch + i)))
countleap++;
}
secs += (countleap * SECSPERDAY);
secs += second;
secs += (hour * SECSPERHOUR);
secs += (minute * SECSPERMIN);
secs += ((day - 1) * SECSPERDAY);
if (month > 1)
{
dayspermonth = 0;
if (LEAPYEAR((epoch + years))) // Only counts when we're on leap day or past it
{
if (month > 2)
{
dayspermonth = 1;
} else if (month == 2 && day >= 29) {
dayspermonth = 1;
}
}
for (i = 0; i < month - 1; i++)
{
secs += (_ytab[dayspermonth][i] * SECSPERDAY);
}
}
return secs;
}
发布于 2011-11-02 19:18:46
首先,不要将秒存储为浮点数。如果您需要微纳秒,请将它们分开存储。你将需要整数来做这些计算。
这取决于你的时区(DST规则,闰年,闰秒),但我想说的是,首先得到天数除以86400的整数。然后通过模除以86400找出剩余的部分。现在,您可以通过第一个整数除以365天数,然后从剩余天数中减去闰日数(通过将天数除以365计算得出),计算出已经过去了多少年。您还需要从剩余秒数(已经计算)中减去闰秒的个数。如果减法使这些数字低于零,则从下一个最大面额中减去。然后,您可以使用日历的显式逻辑来计算月份的第几天。如果你在DST登陆,请确保添加一个小时(或DST偏移量)。
就我个人而言,我只会使用Boost.Date_Time,因为它做了所有这些事情,而且做得更多(可能比你我在最初几次迭代中犯的错误更少),但我想我应该尝试一下你的问题……
https://stackoverflow.com/questions/7960318
复制相似问题