Fun with JavaScript dates and times.

Working with javascript dates can be tricky there are additional libraries you can get and inject into your projects, but I like to keep things dependency-free as far as possible. Especially when a few simple lines is all that was needed.

The date which is returned will be your current local time, this does not help when your API requires time for reporting. eg: all sales between now and now will be empty, as there would in most cases be no transactions happening on this exact millisecond.

You need to convert the date to start at the start of the day, and then to the end of the day, I simply set the hours to 24 hours on the date and then subtract one millisecond.

Subtracting the 1 millisecond is not a solution I have seen online before, most of the solutions online were pretty complicated and or required additional dependencies.

The Code In Action

See the Pen Fun with Javascript Dates by Francois Marais (@francoismarais) on CodePen.

The Javascript


let now = new Date();
let startDate: number;
let endDate: number;
let rangeDates = [];

startDate = new Date(now.setHours(0, 0, 0, 0));

endDate = new Date((now.setHours(24, 0, 0, 0)-1));

//Output to HTML
// Todays Date
document.getElementById("today-now").innerHTML = now;

document.getElementById("today-start").innerHTML = startDate;

document.getElementById("today-end").innerHTML = endDate;

document.getElementById("today-date").innerHTML = startDate.getFullYear() + "/" + startDate.getMonth() + "/" + startDate.getDay() + ' (yy/mm/dd)';


now = new Date();
document.getElementById("today-date-time").innerHTML = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + ' (h:m:s)';


I hope this has helped some of you out there dealing with similar issues. Cheers.

-Francois