Created
June 14, 2021 05:12
-
-
Save hathix/b5434d4a61fe91262018bdea9cce6044 to your computer and use it in GitHub Desktop.
Calendar days ago
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Strips the time part away from a date so that it's a pure date (no time). | |
*/ | |
function toPureDate(d: Date) : Date { | |
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0); | |
} | |
function hoursAgo(h: number) : Date { | |
const now: Date = new Date(); | |
now.setTime(now.getTime() - h * 60 * 60 * 1000); | |
return now; | |
} | |
/** | |
* The number of calendar days that d2 is behind d1. | |
* If d1 is right now, then | |
* If d2 = 0 it's today | |
* If d2 = 1 it's yesterday | |
* If d2 = 2 it's the day before yesterday | |
* If d2 = -1 it's tomorrow | |
*/ | |
function daysAgo(d1: Date, d2: Date) : number { | |
return Math.round( | |
(+toPureDate(d1) - +toPureDate(d2)) / | |
(24 * 60 * 60 * 1000) | |
); | |
} | |
// Testing. Should "roll over" at a certain point. | |
// If it's 8:30pm, then 20 hours ago was 12:30am today (0 days ago) | |
// but 21 hours ago was 11:30pm yesterday (1 day ago). | |
// This is all localized to the current time zone. | |
for (let i = 0; i < 36; i++) { | |
const now = new Date(); | |
const past = hoursAgo(i); | |
console.log(i, toPureDate(past), daysAgo(now, past)); | |
} | |
// Note: I think this solution ignores daylight savings, but eh. | |
// See https://stackoverflow.com/a/11252167 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment