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

Files touched

--- 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 };

Review this PR

Node practice