Categories
JavaScript Answers

How to Get the Start and the End of a Day in JavaScript?

Spread the love

Sometimes, we may want to get the start and end of a day with JavaScript.

In this article, we’ll look at ways to get the start and end of a day with JavaScript.

Using Native Date Methods

One way to get the start and end of a day with JavaScript is to use native date methods.

We can use the setHours method to set the hours of a day to the start or end of a day.

For instance, we can write:

const start = new Date(2020, 1, 1, 1, 1);
start.setHours(0, 0, 0, 0);
console.log(start)

We create the start date with the Date constructor.

Then we call setHours with all zeroes to set the time of the date to midnight.

So start is:

Sat Feb 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)

if we’re in Pacific time.

Likewise, we can use setHours to set the hours, minutes, seconds, and milliseconds to the end of the date.

To do this, we write:

const end = new Date(2020, 1, 1, 1, 1);
end.setHours(23, 59, 59, 999);
console.log(end)

to create a date and set it to the end of the date by passing in a few arguments.

23 is the hours.

The first 59 is the minutes.

The second 59 is the seconds.

And 999 is the milliseconds.

Therefore, end is:

Sat Feb 01 2020 23:59:59 GMT-0800 (Pacific Standard Time)

after calling setHours .

Using Moment.js

Alternatively, we can use the moment.js library to return the start and end of a date.

For instance, we can write:

const start = moment(new Date(2020, 1, 1, 1, 1)).startOf('day');
console.log(start.toString())

to create a moment object with the moment function with a JavaScript native date object as its argument.

Then we call startOf with 'day' to return a moment object with the time set to the start of the day.

So we get:

Sat Feb 01 2020 00:00:00 GMT-0800

as the value of start.toString() if we’re in the Pacific time zone.

Likewise, we can use the endOf method to get the end of the date.

To do this, we write:

const end = moment(new Date(2020, 1, 1, 1, 1)).endOf('day');
console.log(end.toString())

We call endOf instead of startOf .

And then end.toString() returns Sat Feb 01 2020 23:59:59 GMT-0800 if we’re in the Pacific time zone.

We can also convert the time zone to UTC before call startOf and endOf with the utc method.

For instance, we can write:

const start = moment(new Date(2020, 1, 1, 1, 1)).utc().startOf('day');
console.log(start.toString())

const end = moment(new Date(2020, 1, 1, 1, 1)).utc().endOf('day');
console.log(end.toString())

to do the conversion.

Then start.toString() returns:

Sat Feb 01 2020 00:00:00 GMT+0000

And end.toString() returns:

Sat Feb 01 2020 23:59:59 GMT+0000

Conclusion

We can get the start and end of a date with JavaScript with native date methods or moment.js.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *