Categories
Day.js

Manipulating Dates with Day.js — Get the Start or End of a Unit of Time

Spread the love

Day.js is a JavaScript library that lets us manipulate dates in our apps.

In this article, we’ll look at how to use Day.js to manipulate dates in our JavaScript apps.

Get the Start or End of a Unit of Time

We can get the start of a unit of time with the startOf method.

For instance, we can write:

const dayjs = require("dayjs");  
const result = dayjs().startOf("year");  
console.log(result);

to get the date-time of the first day of the year by calling startOf with 'year' .

We can also call startOf with 'year' , 'month' , 'date' , 'hour' , 'minute' , 'second' , and 'millisecond' respectively.

The month starts with 0 for January just like JavaScript dates.

There’re also shorthands for each argument string.

'y' is shorthand for 'year' .

'M' is shorthand for 'month' .

'D' is shorthand for 'date' .

'd' is shorthand for 'day' , which is the day of the week. It starts at 0 for Sunday, and 6 is Saturday.

'h' is shorthand for 'hour' .

'm' is shorthand for 'minute' .

's' is shorthand for 'second' .

And 'ms' is shorthand for 'millisecond' .

We can replace startOf with endOf and keep the same arguments to get the date-time of the end of a given unit of time.

Conclusion

Day.js is a JavaScript library that lets us manipulate dates in our apps.

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 *