Convert a device day count to a calendar year
Node · Node · intermediate · greenfield
Implements dayCountToYear for the device clock: walks forward year by year, subtracting 365 or 366 days depending on whether each year is a leap year, and returns the year the count lands in. Handles leap years; checked against a range of sample day counts.
This runs in the device's real-time clock init; if it does not return, the device hangs at boot with no way for the user to recover except draining the battery.
Requirements
- dayCountToYear takes a 1-based day count since Jan 1, 1980 (day 1 is Jan 1, 1980), a positive integer within the device's 32-bit day counter.
- It must handle leap years correctly (366-day years).
- It must terminate and return a year for every valid day count in that range, including the last day of a leap year (day 366 of a leap year).
Files touched
- src/clock/year.js
--- src/clock/year.js
+const EPOCH_YEAR = 1980;
+
+function isLeapYear(year) {
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
+}
+
+// Convert a 1-based day count since Jan 1, 1980 (day 1 = Jan 1, 1980) into the
+// calendar year it falls in, by walking forward one year at a time and
+// subtracting each year's length. `days` is a positive integer within the
+// device's 32-bit day counter.
+function dayCountToYear(days) {
+ let year = EPOCH_YEAR;
+
+ while (days > 365) {
+ if (isLeapYear(year)) {
+ if (days > 366) {
+ days -= 366;
+ year += 1;
+ }
+ } else {
+ days -= 365;
+ year += 1;
+ }
+ }
+
+ return year;
+}
+
+module.exports = { dayCountToYear, isLeapYear };