Categories
Day.js

Manipulating Dates with Day.js — Minimum Between Multiple Dates and Set Different Date Values

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.

Minimum Between Multiple Dates

To get the maximum of multiple dates, we can use the min method available with the minMax plugin:

const dayjs = require("dayjs");
const minMax = require("dayjs/plugin/minMax");
dayjs.extend(minMax);

const result = dayjs.min(
  dayjs("2020-01-01"),
  dayjs("2018-01-01"),
  dayjs("2019-01-01")
);
console.log(result);

We import the minMax plugin with:

const minMax = require("dayjs/plugin/minMax");

And we get the min date from the dates we passed into the min method.

Set Different Date Values

We can set different date values with the set method and the unit of the date part to set as the argument.

For instance, we write:

const dayjs = require("dayjs");
const result = [
  dayjs().set("year", 2020),
  dayjs().set("month", 1),
  dayjs().set("date", 1),
  dayjs().set("hour", 1),
  dayjs().set("minute", 1),
  dayjs().set("second", 1),
  dayjs().set("millisecond", 1)
];
console.log(result);

to set the year, month, date of the month, hour, minute, second, and milliseconds of a date with the set method and the 'year' , 'month' , 'date' , 'hour' , 'minute' , 'second' , and 'millisecond' values respectively as the first argument.

The 2nd argument is the value to set.

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' .

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 *