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

MySQL database aggregate query and union query operations

Table of contents 1. Insert the queried results 2...

The magic of tbody tag speeds up the display of table content

You must have saved other people’s web pages and l...

Some summary of MySQL's fuzzy query like

1. Common usage: (1) Use with % % represents a wi...

About using Alibaba's iconfont vector icon in Vue

There are many import methods on the Internet, an...

Detailed explanation of Mybatis special character processing

Preface: Mybatis special character processing, pr...

Vue implements book management case

This article example shares the specific code of ...

Examples of using MySQL covering indexes

What is a covering index? Creating an index that ...

IE6 web page creation reference IE6 default style

This is not actually an official document of IE. I...

Determine whether MySQL update will lock the table through examples

Two cases: 1. With index 2. Without index Prerequ...

HTML table tag tutorial (25): vertical alignment attribute VALIGN

In the vertical direction, you can set the row al...

How to open a page in an iframe

Solution: Just set the link's target attribute...

Analysis of the locking mechanism of MySQL database

In the case of concurrent access, non-repeatable ...

MySQL 8.0.15 installation and configuration graphic tutorial

This article records the installation and configu...

Detailed installation tutorial of Mysql5.7.19 under Centos7

1. Download Download mysql-5.7.19-linux-glibc2.12...