How to determine whether a time is the start of a day in vanilla javascript

How to determine whether a time is the start of a day in vanilla javascript

Let’s say you have an endpoint returning the hourly prices for gold. But you don’t want to display hourly values, you want to only display the value at the start of a new day (i.e. at midnight). How do you go about it?

This was a problem I faced working on a project and I settled on a solution which involved creating a function to compare the inputted time -v- the inputted time’s start of day time and returning true or false. If we got a match, then we’d add the inputted time to a new array. This is the function:

function isStartOfDay(epoch) {
     var inputTime = new Date(epoch * 1000).toISOString();
     var startOfDay = new Date(inputTime).setUTCHours(0, 0, 0, 0);
     var epochStartOfDay = Math.round(startOfDay / 1000);
     var result = false;
     if (epoch === epochStartOfDay) {
       result = true;
     }
     return result;
}

// Examples
// isStartOfDay(1559825062) => false
// isStartOfDay(1559779200) => true

In this use case, the times were in epoch format. The quickest way I found to get the start of the inputted time’s day was to use the .toISOString() method to covert the epoch time to a date with UTC offset, then set the date to have 0 hours, minutes, seconds and milliseconds… in other words set the time of the date to 00:00:00 as that is the start of the day. We can do that with the setUTCHours() method.

After that, we basically just compare that date to the original inputted date and return true if it matches. The current epoch time is 1559825062 or 12:44pm UTC. So in this case isStartOfDay(1559825062) would return false. However isStartOfDay(1559779200) will return true because it’s midnight of the 6/6/2019.

A handy epoch conversion tool is available here: https://www.epochconverter.com/. It’s also worth pointing out that you could accomplish this in a single line of code using a library such as Moment.js but as with everything it depends on your own set of circumstances and project. If you’re *just* using a library to accomplish something like this, then it’s like walking in to a restaurant and ordering every item on the menu for dinner knowing you’ll probably only eat one.

Leave a Reply