I'm writing a function that calculates how many days ago a given date was from today. (e.g. yesterday = 1
, last week = 7
, today = 0
, tomorrow = -1
and so on)
Seemed simple enough, and using the JavaScript Date()
function I initially wrote this:
let historicalDate = new Date(2017,05,17).getTime(); // example date: last week
let diff = Math.round((new Date().getTime() - historicalDate) / (24*60*60*1000) );
After I got some weird results, I neatened up the code, but still got the same issue, as follows:
/**
* Returns an integer, representing the number of days since a given date
**/
function getNumDaysFromDate(historicalDate){
const day = 24*60*60*1000; // The number of milliseconds in one day
const now = new Date().getTime(); // The time right now
const then = historicalDate.getTime(); // The time comparing to
return Math.round((now - then) / day ); // Find difference in milliseconds, then days
}
// Test1: last week, should return 7
let creationDate1 = new Date(2017,05,17);
console.log("Last week:", getNumDaysFromDate(creationDate1)); // Fail, prints -23
// Test2: yesterday, should return 1
let creationDate2 = new Date(2017,05,23);
console.log("Yesterday:", getNumDaysFromDate(creationDate2)); // Fail, prints -29
// Test3: Today, should return 0
let creationDate3 = new Date();
console.log("Today:", getNumDaysFromDate(creationDate3)); // Pass, prints 0
// Test4: day affer tomrrow, should return -2
let creationDate4 = new Date(2017,05,26);
console.log("Future:", getNumDaysFromDate(creationDate4)); // Fail, prints -32
All the above results appear to be all about 1 month out, (except for 'test 3', today).
I'm sure there is an obvious or simple reason for this, that one of you will spot instantly, but I have spent the last couple of hours mind-blown by it!
Thanks in advance!
Edit: If possible, I'd like to avoid using a library like Moment.js, as this should be possible nativity (?), and is the only date-related calc in my application.