Julian Day Number:操作系统时间计量的准标准方案
来源:OSDev Wiki· 阅读原文 ↗
文章目录
任何操作系统都需要一种“时间”格式。对于操作系统应从何时开始计量“时间的起点”,似乎并没有真正的标准。但事实上,有一个接近于标准的方案。
基本定义
在天文学中有一种时间度量方式,称为 Julian Day Number(JDN,儒略日数)。由于历史历法系统的原因, 它从公元前 4713 年 1 月 1 日 UTC 正午开始计量时间,并以浮点值按天计量时间。由于它算是一种标准,因此有现成的代码可用于将 JDN 转换为日历日期。
无论如何,一旦你从任何自定义时间格式中分离出秒和秒的小数部分,剩下的就是“天”。 这意味着你的数值与 Julian Day Number 之间的差异仅仅是一个偏移量。当然,也可以截断 JDN, 将其用作整数。
日期计算
Y2K 的 JDN 是 2451545。 如果你假设存在一个“0 年”(或者换种说法,公元前 1 年),那么该年的 1 月 1 日的 JDN 是 1721060。
计算(标准)格里高利日期:400 年恰好有 146097 天。
计算闰年:如果一个年份是 4 的倍数,那么它是闰年,除非它恰好是新世纪的年份且不能被 400 整除。
代码示例
uint32_t days2years[401]; #define LEAP_FLAG 0x80000000 // the days2years table covers 400 years and contains: // 1) the day number at the START of the year // 2) the "century" (year / 100) shifted up 24 bits // 3) a leap year flag void BuildDaysTbl() { int i; int j = 0; uint32_t days = 366; days2years[0] = LEAP_FLAG; while (days < 0x40000000) { i = 24; while (--i >= 0) { days2years[++j] = days; days += 365; days2years[++j] = days; days += 365; days2years[++j] = days; days += 365; days2years[++j] = days | LEAP_FLAG; days += 366; } days2years[++j] = days; days += 365; days2years[++j] = days; days += 365; days2years[++j] = days; days += 365 + 0x10000000; days2years[++j] = days; days += 365; } } // convert a Julian day # to a Gregorian year, with a "remainder", and a leap year flag // outputs: *doy = day of year (jan 1 = 0) with leapyear flag, *cent = century AD uint32_t JDN_to_GregYear(uint32_t jdn, uint16_t *doy, uint32_t *cent) { uint32_t greg_yr = 0; uint32_t qcen, temp, temp2; temp -= 1721060; // make temp align with jan1, "year 0" quadcentury boundary qcen = temp / 146097; // 400 years contain 146097 days temp %= 146097; // get the remainder days within the 400 yr span temp2 = temp; // save a copy // do an approximate conversion to years -- sometimes one too low if (temp > 73048) // calculation for years 200 to 399 { temp -= 73048; // this shifts the calculation by 1 day greg_yr= 200; } greg_yr += (temp << 10) / 374014; // 374014 is a magic number if ((days2years[greg_yr + 1] & 0xfffffff) <= temp2) // fix if greg_yr is off by 1 ++greg_yr; temp = days2years[greg_yr]; *doy = (uint16_t) (temp2 - (temp & 0xfffffff)); *cent = ((temp & 0x30000000) >> 24) + qcen * 4; if ((int32_t) temp < 0) *doy |= 0x8000; // set the leapyear flag on "day of year" return greg_yr; } // convert Jan 1 of a Gregorian year to a Julian day # // "sign" bit of the return value is set on a leap year uint32_t GregYear_to_JDN(uint32_t greg_yr) { uint32_t jdn = (greg_yr / 400) * 146097; // convert quadcenturies to days uint32_t temp = greg_yr % 400; // add in the days from the remaining years, and adjust jan1, "year 0" to actual JDN jdn += (days2years[temp] & 0xfffffff) + 1721060; jdn |= days2years[temp] & 0x80000000; // copy the leap year bit return jdn; }
另请参阅
文章
外部链接
来源与翻译说明
本文根据原文快照翻译,保留原有代码、数值、技术限定及历史背景。原文中的命令与运行结果不代表本站已实际执行验证。
原文:Julian Day Number;离线修订号:24946。

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论