Day.js tutorial

Day.js 教程展示了如何使用 Day.js 模块在 JavaScript 中处理日期和时间。

Day.js

Day.js 是一个极简主义的 JavaScript 日期库,用于解析、验证、操作和格式化日期。它是 Moment.js 的替代库,并且具有很大程度上兼容的 API。 Moment.js 包含在 Moment.js 教程中。

在本文中,我们在 Node 应用程序中使用 Day.js。

设置 Day.js

首先,我们安装 Day.js。

$ npm init -y

我们启动一个新的 Node 应用程序。

$ npm i dayjs

我们使用npm i dayjs 命令安装 Day.js。

Day.js 今天的日期

在第一个示例中,我们使用 Day.js 获取今天的日期。

import dayjs from 'dayjs';

let now = dayjs();

console.log(now.format());

该示例打印当前日期时间。

import dayjs from 'dayjs';

我们加载 Day.js 库。

let now = dayjs();

我们使用dayjs 获取当前本地日期时间对象。

console.log(now.format());

我们用format 格式化输出。默认情况下,我们使用日期时间格式。

$ node now.js
2022-06-16T16:41:57+02:00

输出为 ISO 标准格式。日期时间部分由 T 字符分隔。该字符串以时区结尾。

创建 Day.js 对象

我们可以使用多种方式来创建 datetime Day.js 对象。这些对象被格式化为人类可读的输出。

import dayjs from 'dayjs';

let d1 = dayjs("2018-06-03");
console.log(d1.format());

let d2 = dayjs.unix(1530471537);
console.log(d2.format());

let d3 = dayjs(new Date(2011, 11, 22));
console.log(d3.format());

该示例以三种不同的方式创建日期和时间对象。

let d1 = dayjs("2018-06-03");

我们通过解析字符串创建一个dayjs对象。

let d2 = dayjs.unix(1530471537);
console.log(d2.format());

我们使用 unix 时间戳(以秒为单位)来定义日期时间对象。

let d3 = dayjs(new Date(2011, 11, 22));
console.log(d3.format());

最后,我们使用 JavaScript 内置的 Date 对象来定义一个 dayjs 对象。

$ node create_objects.js
2018-06-03T00:00:00+02:00
2018-07-01T20:58:57+02:00
2011-12-22T00:00:00+01:00

Day.js格式化日期时间

Day.js 对象使用 format 函数格式化。

import dayjs from 'dayjs';

let now = dayjs();

console.log("ISO")
console.log(now.format());

console.log("\nTime")
console.log(now.format("HH:mm:ss"));
console.log(now.format("h:mm:ss a"));

console.log("\nDate")
console.log(now.format("dddd, MMMM D YYYY"));
console.log(now.format("YYYY-MM-DD"));

该示例使用 Day 的 format 函数格式化日期和时间。

$ node formatting.js
ISO
2022-06-16T16:44:39+02:00

Time
16:44:39
4:44:39 pm

Date
Thursday, June 16 2022
2022-06-16

Day.js 计算时间差

使用diff 函数,我们可以计算两个日期时间对象之间的差异。

import dayjs from 'dayjs';

const date1 = dayjs("2019-14-05");
const date2 = dayjs("2018-06-25");

let df1 = date1.diff(date2);
console.log(df1);

let df2 = date1.diff(date2, "month");
console.log(df2);

let df3 = date1.diff(date2, "month", true);
console.log(df3);

let df4 = date1.diff(date2, "day");
console.log(df4);

let df5 = date1.diff(date2, "week");
console.log(df5);

该示例计算两个 dayjs 对象在月、日和周之间的差异。

let df2 = date1.diff(date2, "month");
console.log(df2);

第二个参数表示输出将以月为单位。

let df3 = date1.diff(date2, "month", true);
console.log(df3);

将第三个参数设置为true 返回一个浮点值,例如7.3 个月。

$ node difference.js
19357200000
7
7.3
224
32

Borodino 战役是 1812 年 9 月 7 日法国入侵俄罗斯期间拿破仑战争中的一场战役。

import dayjs from 'dayjs';

let borodinoBattle = dayjs('1812-09-07');

let now = dayjs();
let days = now.diff(borodinoBattle, 'days');

console.log(`On ${now.format('YYYY-MM-DD')}, ${days} days have passed since the Borodino battle.`);

在示例中,我们计算自著名战役以来经过的天数。

$ node borodino.js
On 2022-06-16, 76618 days have passed since the Borodino battle.

Day.js 日期时间算法

add 函数用于将日期和时间添加到 dayjs 对象,subtract 函数用于从 dayjs 对象中减去日期和时间。

import dayjs from 'dayjs';

let now = dayjs();

console.log(now.format('YYYY-MM-DD'));

let d1 = now.add('14', 'day');

console.log(d1.format('YYYY-MM-DD'));

let d2 = now.subtract('3', 'year');

console.log(d2.format('YYYY-MM-DD'));

在示例中,我们将当前日期时间加上十四天并减去两年。

let d1 = now.add('14', 'day');
...
let d2 = now.subtract('3', 'year'););

addsubtract函数的第二个参数是单元类型。

$ node arithm.js
2022-06-16
2022-06-30
2019-06-16

Day.js 日期时间部分

在下面的示例中,我们获取当前日期时间的各个部分。

import dayjs from 'dayjs';

let now = dayjs();

console.log(now);

let year = now.year();
console.log(`Year: ${year}`);

let month = now.month();
console.log(`Month: ${month}`);

let date = now.date();
console.log(`Date: ${date}`);

let hour = now.hour();
console.log(`Hour: ${hour}`);

let minute = now.minute();
console.log(`Minute: ${minute}`);

let second = now.second();
console.log(`Second: ${second}`);

let milli = now.millisecond();
console.log(`Millisecond: ${milli}`);

该示例计算当前日期时间。我们获取日期时间的年、月、日、时、分、秒和毫秒部分。

$ node parts.js
M {
  '$L': 'en',
  '$d': 2022-06-16T14:48:25.918Z,
  '$x': {},
  '$y': 2022,
  '$M': 5,
  '$D': 16,
  '$W': 4,
  '$H': 16,
  '$m': 48,
  '$s': 25,
  '$ms': 918
}
Year: 2022
Month: 5
Date: 16
Hour: 16
Minute: 48
Second: 25
Millisecond: 918

Day.js 转换函数

除了format函数,我们还可以使用一些内置的转换函数。

import dayjs from 'dayjs';

let now = dayjs();

console.log(now.toString());
console.log(now.toJSON());
console.log(now.toISOString());

我们有三个函数。 toJSONtoISOString 的别名。

$ node converting.js
Thu, 16 Jun 2022 14:49:35 GMT
2022-06-16T14:49:35.718Z
2022-06-16T14:49:35.718Z

Day.js 相对日期时间

我们可以使用startOfendOf 函数计算相对日期时间。

import dayjs from 'dayjs';

// let now = dayjs();

let startWeek = dayjs().startOf('week');
console.log(startWeek.format());

let endWeek = dayjs().endOf('week');
console.log(endWeek.format());

let startMonth = dayjs().startOf('month');
console.log(startMonth.format());

let endMonth = dayjs().endOf('month');
console.log(endMonth.format());

let startYear = dayjs().startOf('year');
console.log(startYear.format());

let endYear = dayjs().endOf('year');
console.log(endYear.format());

该示例使用上述函数。

let startWeek = dayjs().startOf('week');
console.log(startWeek.format());

这里我们计算本周开始的日期时间。

let endYear = dayjs().endOf('year');
console.log(endYear.format());

在这里我们得到了一年中的最后一个日期时间。

$ node relative_time.js
2022-06-12T00:00:00+02:00
2022-06-18T23:59:59+02:00
2022-06-01T00:00:00+02:00
2022-06-30T23:59:59+02:00
2022-01-01T00:00:00+01:00
2022-12-31T23:59:59+01:00

Day.js 校验有效性

我们可以使用isValid 函数来检查日期和时间对象是否有效。

import dayjs from 'dayjs';

let day1 = dayjs('2018-12-12');
let day2 = dayjs('2018-11-ks');

if (day1.isValid()) {

    console.log("Day is valid");
    console.log(day1.format());
} else {

    console.log("Day is not valid");
}

if (day2.isValid()) {

    console.log("Day is valid");
    console.log(day2.format());
} else {

    console.log("Day is not valid");
}

该示例检查两天的有效性。

Day.js 日期查询

isSameisBeforeisAfter 函数可用于确定一个日期是在另一个日期之前还是之后。

import dayjs from 'dayjs';

let d1 = dayjs("2018-05-19");
let d2 = dayjs("2018-05-20");
let d3 = dayjs("2018-05-22");
let d4 = dayjs("2018-05-19");

if (d1.isSame(d4)) {

    console.log('these are same dates');
} else {

    console.log('these are not the same dates');
}

if (d1.isAfter(d2)) {

    console.log(`${d1.format('YYYY-MM-DD')} is after ${d2.format('YYYY-MM-DD')}`);
} else {

    console.log(`${d1.format('YYYY-MM-DD')} is before ${d2.format('YYYY-MM-DD')}`);
}

if (d2.isBefore(d3)) {

    console.log(`${d2.format('YYYY-MM-DD')} is before ${d3.format('YYYY-MM-DD')}`);
} else {

    console.log(`${d2.format('YYYY-MM-DD')} is after ${d3.format('YYYY-MM-DD')}`);
}

在示例中,我们比较了三个日期。

$ node queries.js
these are same dates
2018-05-19 is before 2018-05-20
2018-05-20 is before 2018-05-22

isBetween 函数检查日期是否在给定的日期范围内。

import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween.js';

dayjs.extend(isBetween);

let d1 = dayjs("2018-05-19");

if (d1.isBetween('2018-05-10', '2018-05-25')) {

    console.log("The day is within the date range");
} else {

    console.log("The day is not within the date range");
}

该示例使用isBetween 函数来确定日期是否在指定的日期范围内。对于此示例,我们需要isBetween 插件。

Day.js unix时间

Unix time 是自 Unix 纪元以来的秒数。unix 函数返回以秒为单位的时间值,自 1970 年 1 月 1 日 0 小时 0 分 0 秒起,Coordinated Universal时间。

import dayjs from 'dayjs';

let unixTime_s = dayjs().unix();
console.log(unixTime_s);

let unixTime_ms = dayjs().valueOf();
console.log(unixTime_ms);

let unixTime2 = dayjs(1);
console.log(unixTime2.format('YYYY-DD-MM'));

在示例中,我们获取当前 unix 时间并将 unix 时间 1 转换为人类可读格式。

let unixTime_s = dayjs().unix();

我们使用unix 函数获取Unix 时间。返回值是从 Unix 纪元开始经过的秒数。

let unixTime_ms = dayjs().valueOf();

使用valueOf 函数,我们得到以毫秒为单位的 Unix 时间。

let unixTime2 = dayjs(1);
console.log(unixTime2.format('YYYY-DD-MM'));

我们得到 1 s 的 unix 时间并以给定的格式输出它。

$ node unix_time.js
1655391820
1655391820977
1970-01-01

Day.js 闰年

闰年是包含额外一天的年份。日历中多出一天的原因是天文年和日历年之间的差异。我们需要添加 isLeapYear 插件。

import dayjs from 'dayjs';
import isLeapYear from 'dayjs/plugin/isLeapYear.js';

dayjs.extend(isLeapYear)

// Assume year >= 1582 in the Gregorian calendar.

let years = [ 2000, 2002, 2004, 2008, 2012, 2016, 2020,
    1900, 1800, 1600 ];

for (const year of years) {

    let ym = dayjs([year]);

    if (ym.isLeapYear()) {

        console.log(`${year} is a leap year`);
    } else {

        console.log(`${year} is not a leap year`);
    }
}

在示例中,我们有一个年份数组。我们确定哪些年份是闰年。

if (ym.isLeapYear()) {

我们使用isLeapYear函数判断某年是否为闰年。

$ node leap_year.js
2000 is a leap year
2002 is not a leap year
2004 is a leap year
2008 is a leap year
2012 is a leap year
2016 is a leap year
2020 is a leap year
1900 is not a leap year
1800 is not a leap year
1600 is a leap year

在本文中,我们使用 Day.js 库在 JavaScript 中处理日期和时间。

列出所有 JavaScript 教程。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏