最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

algorithm - Changing base of unix timestamp calculation to 1.1.2025 - Stack Overflow

programmeradmin3浏览0评论

I want to write my own version of ctime() which converts a timestamp to a human readable format. I found the following algorithm which is used in several projects (like .c#L230 and .c#L75), but nobody really documented how it works:

//Convert Unix time to date
a = (uint32_t) ((4 * t + 102032) / 146097 + 15);
b = (uint32_t) (t + 2442113 + a - (a / 4));
c = (20 * b - 2442) / 7305;
d = b - 365 * c - (c / 4);
e = d * 1000 / 30601;
f = d - e * 30 - e * 601 / 1000;
  
//January and February are counted as months 13 and 14 of the previous year
if(e <= 13)
{
   c -= 4716;
   e -= 1;
}
else
{
   c -= 4715;
   e -= 13;
}
  
//Retrieve year, month and day
date->year = c;
date->month = e;
date->day = f;

In some places there is even a comment "I don't know how this works but everyone uses it". I have found out that the base of this algorithm seems to be one that calculates a "Julian Date" to a "Gregorian Date". The interesting part seems to be the calculation of a and b.

Can someone break down what this algorithm does and which constants need to be adapted so it uses "days since 1.1.2025" as new base?

发布评论

评论列表(0)

  1. 暂无评论