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

Ubuntu16.04 installation mysql5.7.22 graphic tutorial

VMware12.0+Ubuntu16.04+MySQL5.7.22 installation t...

MySQL database query performance optimization strategy

Optimize queries Use the Explain statement to ana...

How to Install Oracle Java 14 on Ubuntu Linux

Recently, Oracle announced the public availabilit...

Docker builds CMS on-demand system with player function

Table of contents text 1. Prepare the machine 2. ...

N ways to center elements with CSS

Table of contents Preface Centering inline elemen...

WeChat applet to determine whether the mobile phone number is legal example code

Table of contents Scenario Effect Code Summarize ...

Implementation of Vue package size optimization (from 1.72M to 94K)

1. Background I recently made a website, uidea, w...

Vue: Detailed explanation of memory leaks

What is a memory leak? A memory leak means that a...

Summary of the Differences between SQL and NoSQL

Main differences: 1. Type SQL databases are prima...

Best Practices for Developing Amap Applications with Vue

Table of contents Preface Asynchronous loading Pa...

Javascript uses the integrity attribute for security verification

Table of contents 1. Import files using script ta...

Use CSS content attr to achieve mouse hover prompt (tooltip) effect

Why do we achieve this effect? ​​In fact, this ef...

Vue uses rules to implement form field validation

There are many ways to write and validate form fi...

Example code of CSS layout at both ends (using parent's negative margin)

Recently, during the development process, I encou...

Detailed explanation of JavaScript clipboard usage

(1) Introduction: clipboard.js is a lightweight J...