More elegant processing of dates in JavaScript based on Day.js

More elegant processing of dates in JavaScript based on Day.js

Today I recommend a library Day.js to everyone, which can help us deal with dates in JavaScript, because the dates in JavaScript are too difficult to use. It is completely unusable when doing business development, and you need to encapsulate various functions yourself.

Why use day.js

First of all, using day.js can help us more easily handle dates and times in JavaScript.
You may have heard of many libraries for processing time in JavaScript, such as Moment, but it is 2021, and it is actually not recommended to use moment.js, because as a date processing tool, it is too cumbersome. day.js is a more modern, lightweight, and easier to expand library.

Moment.js

Click here to view size

Day.js

Click here to view size

It is very lightweight because it can use TreeShaking and be extended through plug-ins. We can introduce plug-ins according to our needs, so we will only introduce what we need in the end.

What would we do without day.js?

In native JavaScript, we need to get the current date like this

const today = new Date();
const dd = String(today.getDate()).padStart(2, '0'); // day const mm = String(today.getMonth() + 1).padStart(2, '0'); // month const yyyy = today.getFullYear(); // year const curDate = `${yyyy}-${mm}-${dd}`

console.log(curDate)
// Output: 2021-09-17

In day.js, we only need this, of course, it supports more than that, and many other functions.
import dayjs from "dayjs";

const curDate = dayjs().format('YYYY-MM-DD');

console.log(curDate)
// Output: 2021-09-17

Day.js Example

Now let's look at some practical and interesting examples that are simpler and more readable than the native API.

1. Get the number of days between two dates

View Documentation

import dayjs from "dayjs";

// The second parameter is specified as 'day', which means the granularity is day.dayjs(new Date(2021, 10, 1)).diff(new Date(2021, 9, 17), "day"); 
// Output: 15

2. Check if the date is valid

View Documentation

import dayjs from "dayjs";

dayjs("20").isValid(); 
// Output: false
dayjs("2021-09-17").isValid(); 
// Output: true

3. Get the number of days in the month of the input date

View Documentation

import dayjs from "dayjs";

dayjs("2021-09-13").daysInMonth() 
// Output: 30

4. Add day, month, year, hour, minute, second

View Documentation

import dayjs from "dayjs";

dayjs("2021-09-17 08:10:00").add(20, "minute").format('YYYY-MM-DD HH:mm:ss') 
// Output: 2021-09-17 08:30:00

5. Subtract days, months, years, hours, minutes, and seconds

View Documentation

import dayjs from "dayjs";

dayjs("2021-09-17 08:10:00").subtract(20, "minute").format('YYYY-MM-DD HH:mm:ss')
// Output: 2021-09-17 07:50:00

Use plugins to extend functionality

1. RelativeTime

View Documentation

Get the time difference from the specified time to now.

import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";

dayjs.extend(relativeTime);

dayjs("2021-09-16 13:28:55").fromNow();
// Output: 9 hours ago

Below is all the output tables

Range Key Sample Output
0 to 44 seconds s a few seconds ago
45 to 89 seconds m a minute ago
90 seconds to 44 minutes mm 2 minutes ago ... 44 minutes ago
45 to 89 minutes h an hour ago
90 minutes to 21 hours hh 2 hours ago ... 21 hours ago
22 to 35 hours d a day ago
36 hours to 25 days dd 2 days ago ... 25 days ago
26 to 45 days M a month ago
46 days to 10 months MM 2 months ago ... 10 months ago
11 to 17 months y a year ago
18 months+ yy 2 years ago ... 20 years ago

2. WeekOfYear

View Documentation

Get the week number of the specified date in the year

import dayjs from "dayjs";
import weekOfYear from "dayjs/plugin/weekOfYear";

dayjs.extend(weekOfYear);

dayjs("2021-09-13 14:00:00").week(); 
// Output: 38

3. IsSameOrAfter

View Documentation

Checks if a date is equal to or greater than a date

import dayjs from "dayjs";
import isSameOrAfter from "dayjs/plugin/isSameOrAfter";

dayjs.extend(isSameOrAfter);

dayjs("2021-09-17").isSameOrAfter("2021-09-16"); 
// Output: true

4. MinMax

View Documentation

Get the largest or smallest date in an array

import dayjs from "dayjs";
import minMax from "dayjs/plugin/minMax";

dayjs.extend(minMax)

const maxDate = dayjs.max([
    dayjs("2021-09-13"), 
    dayjs("2021-09-16"), 
    dayjs("2021-09-20")
])

const minDate = dayjs.min([
    dayjs("2021-09-13"), 
    dayjs("2021-09-16"), 
    dayjs("2021-09-20")
])

maxDate.format('YYYY-MM-DD HH:mm:ss') 
// Output: 2021-09-20 00:00:00
minDate.format('YYYY-MM-DD HH:mm:ss') 
// Output: 2021-09-13 00:00:00

5. IsBetween

View Documentation

Checks whether a specified date is within a specified date range

import dayjs from "dayjs";
import isBetween from "dayjs/plugin/isBetween";

dayjs.extend(isBetween);

// Use day as the granularity for comparison dayjs("2010-10-21").isBetween(dayjs("2010-10-20"), dayjs("2010-10-25"), "day");
// Output: true

// Use year as the granularity for comparison dayjs("2010-10-21").isBetween(dayjs("2010-10-20"), dayjs("2010-10-25"), "year");
// Output: false

This concludes this article on more elegant date processing in JavaScript based on Day.js. For more information about date processing with Day.js, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief discussion on JS date processing function
  • Moment.js is an awesome Javascript date processing library that you shouldn't miss.
  • 5 Best JavaScript Date Processing Libraries
  • How to display the date of last week and last month in javascript
  • Date processing js library (mini version)--Summary of self-built js library
  • A javascript date processing function organized by myself
  • Detailed explanation of general date format processing, calendar rendering and countdown functions in js
  • JavaScript date processing function, performance optimization batch processing

<<:  In-depth analysis of why MySQL does not recommend using uuid or snowflake id as primary key

>>:  How to use gdb to debug core files in Linux

Recommend

Detailed explanation of Mysql transaction processing

1. MySQL transaction concept MySQL transactions a...

A brief discussion on the placement of script in HTML

I used to think that script could be placed anywh...

Detailed explanation of Vue custom instructions and their use

Table of contents 1. What is a directive? Some co...

How to use the markdown editor component in Vue3

Table of contents Install Importing components Ba...

Linux kernel device driver memory management notes

/********************** * Linux memory management...

Summary of Mysql-connector-java driver version issues

Mysql-connector-java driver version problem Since...

Vue implements an example of pulling down and scrolling to load data

Table of contents Step 1: Installation Step 2: Ci...

Detailed graphic explanation of mysql query control statements

mysql query control statements Field deduplicatio...

Share some tips on using JavaScript operators

Table of contents 1. Optional chaining operator [...

Detailed explanation of chmod command usage in Linux

chmod Command Syntax This is the correct syntax w...

Introducing icons by implementing custom components based on Vue

Preface In project development, there are many wa...

Vue-cli creates a project and analyzes the project structure

Table of contents 1. Enter a directory and create...