Open In App

JavaScript Get the start and end of the day in UTC

Given a date, and the task is to determine the start and end of the day of the date using JavaScript. We’re going to discuss a few methods. These are:

JavaScript setHours() Method: This method sets the hour of a date object. This method can be used to set the minutes, seconds, and milliseconds.



 Syntax:

Date.setHours(hour, min, sec, millisec)

Parameters:



JavaScript toUTCString() Method: This method converts a Date object to a string, depending on universal time.

 Syntax: 

Date.toUTCString()

Return Value: It returns a string, representing the UTC date and time as a string.

Example 1: This example gets the first millisecond of the day and last millisecond of the day as well using setHours() method and converting it to UTC format using stoUTCString() method.




let startOfDay = new Date();
startOfDay.setHours(0, 0, 0, 0);
 
let endofDay = new Date();
endofDay.setHours(23, 59, 59, 999);
 
console.log(startOfDay.toUTCString());
console.log(endofDay.toUTCString());

Output

Tue, 13 Jun 2023 18:30:00 GMT gfg.html:8:9
Wed, 14 Jun 2023 18:29:59 GMT

Example 2: This example gets the first millisecond of the day and last millisecond of the day but by a different approach than previous one using setHours() method and converting it to UTC format using stoUTCString() method.




let startOfDay = new Date();
startOfDay.setHours(0, 0, 0, 0);
 
let endofDay = new Date();
endofDay.setHours(24, 0, 0, -1);
 
console.log(startOfDay.toUTCString());
console.log(endofDay.toUTCString());

Output

Tue, 13 Jun 2023 18:30:00 GMT
Wed, 14 Jun 2023 18:29:59 GMT

We have a complete list of JavaScript Date Objects, to check those please go through this JavaScript Date Object Complete reference article.


Article Tags :