Categories
JavaScript Answers

How to Remove Time from a Date with Moment.js?

Spread the love

Sometimes, we want to remove the time portion of a date from the date in our JavaScript app.

We can do this easily with the moment.js library.

In this article, we’ll look at how to remove the time portion of a date with moment.js.

The startOf Method

We can remove the time portion from a date with the startOf method.

For instance, we can write:

const day = moment(new Date(2021, 1, 1, 1, 1)).startOf('day')  
console.log(day.toDate())

We pass in a date with the hour and minutes set into the moment function.

Then we call startOf with the 'day' argument to get return a moment object with the time set to midnight of the same date.

Then we call toDate to convert it back to a native JavaScript date.

And so we get:

Mon Feb 01 2021 00:00:00 GMT-0800 (Pacific Standard Time)

as the result if our device’s time is in the Pacific time zone.

The format Method

The format method lets us format a date the way we want.

We can pass in the 'LL' formatting code to return a date string with only the date portion of a date.

For instance, we can write:

const day = moment(new Date(2021, 1, 1, 1, 1)).format('LL')  
console.log(day)

We create the moment object the same way.

But after that, we call format with the 'LL' formatting code.

Then day would be the following date string:

'February 1, 2021'

Also, we can pass in 'L' to get the date string in MM/DD/YYYY format.

So we can write:

const day = moment(new Date(2021, 1, 1, 1, 1)).format('L')  
console.log(day)

And we get:

'02/01/2021'

as the value of day .

We can also use MM to get the 2 digit month. DD gets the 2 digit day. And YYYY gets the 4 digit year.

So we can write:

const day = moment(new Date(2021, 1, 1, 1, 1)).format('MM/DD/YYYY')  
console.log(day)

to get the same result as with 'L' .

MMMM gets the full month name, D gets the day number without the leading zero padding.

So we can write:

const day = moment(new Date(2021, 1, 1, 1, 1)).format('MMMM D, YYYY')  
console.log(day)

to get the same date string as 'LL' .

Conclusion

We can use the startOf method to return a moment date object without the time portion of a date.

Also, we can use the format method to return a date string without the time portion of a date.

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 *