The Javascript Date Object is a complicated thing. It seems very straightforward. A date object holds a numerical value representing the number of milliseconds since January 1st 1970. This value can then be added or subtracted from other date objects to do calendar calculations. The example below illustrates the conversions that are built into the date object. Fortunately, the constructor for the date object can take a month a day and a year, or a string representing them and parse them into a date.
const sampledays = 2 * (1000*60*60*24);
const millisecondsToDays = (milliseconds)=>{
let days;
days = milliseconds/(1000*60*60*24);
return days;
};
console.log(millisecondsToDays(sampledays));
Another confusing factor is that people format dates in differents ways. Some use day/month/year while others use month/day/year. There are others that argue for a logical year/month/day which can easily add /hour/minute/second depending on the precision required. The constructor for date objects also accepts values for months from 0-11 as arrays start at 0 not 1. These headaches are annoying but there are a number of clever solutions to reformat them.
// The following are examples of different date formats
let dateExample = 12/25/2022;
let dateExample2 = 25/12/2022;
let dateExample3 = 2022/12/25/12/45;
// Notice in the date constructor December is 11
const christmasEve = new Date(2022, 11, 24);
Finally, the biggest hurdle for date handling is time zones. The internet is incredible as information is sent around the world in seconds. The drawback is that information is being passed back and forth between people in different timezones or even calendar days. To account for This it would seem to be simple, offset by the number of time zones. The world of course is not that simple. There are exceptions such as daylight savings that throw everything off. Some countries do not observe daylight savings, others do but they have different dates for it. This is where the precision of the date object can throw off date calculations.
let newYearsEve = "2022-12-31";
const daysUntil = (finalDate) => {
let endDate = new Date(finalDate);
let today = new Date();
let daysLeft = (endDate - today)/1000/60/60/24;
return daysLeft;
}
console.log(daysUntil(newYearsEve));
This method will return the number of days left until New Year's Eve except it is short by one day. This is because the timezone is not specified. In the following example the timezone is concatenated onto the string entered into the constructor. This will account for the difference and return the correct answer.
let newYearsEve = "2022-12-31";
const daysUntil = (finalDate) => {
let endDate = new Date(finalDate + " CST");
let today = new Date();
let daysLeft = (endDate - today)/1000/60/60/24;
return daysLeft;
}
console.log(daysUntil(newYearsEve));