Moment.js 教程
最后修改于 2023 年 10 月 18 日
在本文中,我们将展示如何使用 Moment.js 模块在 JavaScript 中处理日期和时间。
Moment.js
Moment.js 是一个轻量级的 JavaScript 日期库,用于解析、验证、操作和格式化日期。
在本文中,我们在 Node 应用程序中使用 Moment.js。 还有一个类似的 Day.js 库,在 Day.js 教程 中有介绍。
设置 Moment.js
首先,我们安装 Moment.js。
$ npm init
我们启动一个新的 Node 应用程序。
$ npm i moment
我们使用 npm i moment 命令安装 Moment.js。
Moment.js 获取今天的日期
在第一个示例中,我们使用 Moment.js 获取今天的日期。
const moment = require('moment');
let now = moment();
console.log(now.format());
该示例打印今天的日期和时间。
const moment = require('moment');
我们加载 Moment.js 库。
let now = moment();
我们使用 moment 获取当前的本地日期时间对象。
console.log(now.format());
我们使用 format 格式化输出。 默认情况下,我们获得长日期时间格式。
$ node today.js 2018-07-01T16:32:53+02:00
这是 ISO 标准格式。 日期和时间部分由 T 字符分隔。 字符串以时区结尾。
创建 Moment.js 对象
我们可以使用多种方法来创建日期和时间 Moment.js 对象。 稍后必须格式化这些对象才能转换为人类可读的格式。
const moment = require('moment');
let d1 = moment("2018-06-03");
console.log(d1.format('ll'));
let d2 = moment([2017, 11, 23]);
console.log(d2.format('ll'));
let d3 = moment({ year :2010, month :3, day :5,
hour :15, minute :10, second :3, millisecond :123});
console.log(d3.format('ll'));
let d4 = moment(1530471537000);
console.log(d4.format('ll'));
let d5 = moment(new Date(2011, 11, 22));
console.log(d5.format('ll'));
该示例以五种不同的方式创建日期和时间对象。
let d1 = moment("2018-06-03");
我们从字符串创建 moment 对象。
let d2 = moment([2017, 11, 23]);
console.log(d2.format('ll'));
这里从数组创建 moment 对象。
let d3 = moment({ year :2010, month :3, day :5,
hour :15, minute :10, second :3, millisecond :123});
console.log(d3.format('ll'));
我们可以使用 JSON 对象来创建 moment 对象。
let d4 = moment(1530471537000);
console.log(d4.format('ll'));
我们使用 Unix 时间戳(以毫秒为单位)来定义 moment 对象。
let d5 = moment(new Date(2011, 11, 22));
console.log(d5.format('ll'));
最后,我们使用 JavaScript 内置的 Date 对象来定义 moment 对象。
$ node create_moment_objects.js Jun 3, 2018 Dec 23, 2017 Apr 5, 2010 Jul 1, 2018 Dec 22, 2011
Moment.js 格式化日期时间
Moment.js 对象使用 format 函数进行格式化。 也有本地化格式的选项。
const moment = require('moment');
let now = moment();
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 Do YYYY"));
console.log(now.format("YYYY-MM-DD"));
console.log("\nLocalized")
console.log(now.format("LT"));
console.log(now.format("LTS"));
console.log(now.format("LTS"));
console.log(now.format("L"));
console.log(now.format("l"));
该示例使用 Moment 的 format 函数格式化日期和时间。
$ node format.js ISO 2018-07-03T10:09:47+02:00 Time 10:09:47 10:09:47 am Date Tuesday, July 3rd 2018 2018-07-03 Localized 10:09 AM 10:09:47 AM 10:09:47 AM 07/03/2018 7/3/2018
Moment.js 计算日期时间差
使用 diff 函数,我们可以计算两个日期时间对象之间的差值。
const moment = require('moment');
let d1 = moment('2018-06-12');
let d2 = moment('2018-06-28');
let days = d2.diff(d1, 'days');
console.log(`Difference in days: ${days}`);
let hours = d2.diff(d1, 'hours');
console.log(`Difference in hours: ${hours}`);
该示例计算两个 moment 对象之间的天数和小时差。
let days = d2.diff(d1, 'days');
第二个参数表示输出将以天为单位。
$ node difference.js Difference in days: 16 Difference in hours: 384
博罗季诺战役是 1812 年 9 月 7 日在拿破仑战争期间法国入侵俄国期间发生的一场战役。
const moment = require('moment');
let borodinoBattle = moment('1812-09-07');
let now = moment();
let days = now.diff(borodinoBattle, 'days');
console.log(`On ${now.format('ll')}, ${days} days have passed since the Borodino battle.`);
在该示例中,我们计算自那时以来经过的天数。
$ node borodino.js On Jul 3, 2018, 75174 days have passed since the Borodino battle.
Moment.js 日期时间运算
add 函数用于将日期和时间添加到 moment 对象,而 subtract 函数从 moment 对象中减去日期和时间。
const moment = require('moment');
let now = moment();
console.log(`Now: ${now.format('ll')}`);
now.add('3', 'days');
console.log(`Adding three days: ${now.format('ll')}`);
now.subtract('2', 'years');
console.log(`Subtracting 2 years: ${now.format('ll')}`);
在该示例中,我们添加三天并减去两年。
now.add('3', 'days');
...
now.subtract('2', 'years');
add 和 subtract 方法的第二个参数是单位类型。
$ node add_sub.js Now: Jul 1, 2018 Adding three days: Jul 4, 2018 Subtracting 2 years: Jul 4, 2016
Moment.js 日期时间部分
在以下示例中,我们获取当前日期时间的部分。
const moment = require('moment');
let now = moment();
let year = now.get('year');
let month = now.get('month'); // 0 to 11
let date = now.get('date');
let hour = now.get('hour');
let minute = now.get('minute');
let second = now.get('second');
let millisecond = now.get('millisecond');
console.log("Year: " + year);
console.log("Month: " + month);
console.log("Date: " + date);
console.log("Hour: " + hour);
console.log("Minute: " + minute);
console.log("Second: " + second);
console.log("Millisecond: " + millisecond);
该示例计算当前日期时间。 我们获取日期时间的年、月、日、小时、分钟、秒和毫秒部分。
$ node parts.js Year: 2018 Month: 6 Date: 2 Hour: 18 Minute: 10 Second: 3 Millisecond: 329
Moment.js 星期几、月份、年份
以下示例计算星期几、月份和年份。
const moment = require('moment');
let now = moment();
console.log("Day of week: " + now.weekday());
console.log("Day of month: " + now.date());
console.log("Day of year: " + now.dayOfYear());
weekday 返回星期几,date 返回月份中的天数,dayOfYear 返回一年中的天数。
$ node main.js Day of week: 1 Day of month: 2 Day of year: 183
Moment.js 一年中的周、季度、一年中的周数
在以下示例中,我们获取一年中的周数、一年中的季度数以及一年中的周数。
const moment = require('moment');
let now = moment();
console.log("Week of year: " + now.week());
console.log("Quarter of year: " + now.quarter());
console.log("Weeks in year: " + now.weeksInYear());
week 方法返回一年中的周数,quarter 返回一年中的季度数,weeksInYear 返回一年中的周数。
$ node weeks_quarter.js Week of year: 27 Quarter of year: 3 Weeks in year: 52
Moment.js 相对日期时间
我们可以使用 fromNow、startOf 和 endOf 函数计算相对日期时间。
const moment = require('moment');
let day = moment().startOf('year');
let now = moment();
let days = now.diff(day, 'days');
console.log(`${days} have passed since the start of the year.`);
let val = moment().endOf('day');
let mins = val.diff(now, 'minutes');
console.log(`The day will end in ${mins} minutes.`);
let day2 = moment("2028-12-20")
let diff = day2.fromNow();
console.log(`The day will come ${diff}.`);
该示例使用上述函数。
let day = moment().startOf('year');
let now = moment();
let days = now.diff(day, 'days');
在这里,我们计算自年初以来经过的天数。
let val = moment().endOf('day');
let mins = val.diff(now, 'minutes');
这些行计算到午夜的分钟数。
let day2 = moment("2028-12-20")
let diff = day2.fromNow();
在这里,我们获取到指定日期的年数。
$ node relative_time.js 182 have passed since the start of the year. The day will end in 360 minutes. The day will come in 10 years.
Moment.js 检查有效性
我们可以使用 isValid 方法来检查日期和时间对象是否有效。
const moment = require('moment');
let day1 = moment('2018-12-12');
let day2 = moment('2018-13-12');
if (day1.isValid()) {
console.log("Day is valid");
} else {
console.log("Day is not valid");
}
if (day2.isValid()) {
console.log("Day is valid");
} else {
console.log("Day is not valid");
}
该示例检查两个日期的有效性。
Moment.js 日期查询
可以使用 isBefore 和 isAfter 函数来确定日期是否早于或晚于另一个日期。
const moment = require('moment');
let d1 = moment("2018-05-19");
let d2 = moment("2018-05-20");
let d3 = moment("2018-05-22");
if (d1.isAfter(d2)) {
console.log(`${d1.format('ll')} is after ${d2.format('ll')}`);
} else {
console.log(`${d1.format('ll')} is before ${d2.format('ll')}`);
}
if (d2.isBefore(d3)) {
console.log(`${d2.format('ll')} is before ${d3.format('ll')}`);
} else {
console.log(`${d2.format('ll')} is after ${d3.format('ll')}`);
}
在该示例中,我们使用 isBefore 和 isAfter 函数比较三个日期。
$ node date_queries.js May 19, 2018 is before May 20, 2018 May 20, 2018 is before May 22, 2018
isBetween 函数检查日期是否在给定的日期范围内。
const moment = require('moment');
let d1 = moment("2018-05-19");
if (d1.isBetween('2018-05-10', '2018-05-25')) {
console.log("The day is within the date range");
}
该示例使用 isBetween 函数来确定日期是否在指定的日期范围内。
Moment.js Unix 时间
Unix 时间 是自 Unix 纪元以来的秒数。 unix 函数返回自协调世界时 1970 年 1 月 1 日 0 时 0 分 0 秒以来以秒为单位的时间值。
const moment = require('moment');
let unixTime = moment().unix();
console.log(unixTime);
let unixTime2 = moment(1000);
console.log(unixTime2.format('MM-DD-YYYY'));
在该示例中,我们获取当前的 Unix 时间并将 Unix 时间 1 秒转换为人类可读的格式。
let unixTime = moment().unix();
我们使用 unix 函数获取 Unix 时间。 返回值是从 Unix 纪元开始经过的秒数。
let unixTime2 = moment(1000);
console.log(unixTime2.format('MM-DD-YYYY'));
我们获取 1 秒的 Unix 时间并以给定格式输出。
$ node unixtime.js 1530606134 01-01-1970
Moment.js 解析日期和时间
我们可以通过将日期和时间格式传递给 moment 函数来解析日期和时间的字符串表示形式。
const moment = require('moment');
let day = "03/04/2008";
let parsed = moment(day, "DD/MM/YYYY");
console.log(parsed.format('ll'));
在该示例中,我们解析一个非标准的日期和时间字符串。 我们将预期的格式作为 moment 函数的第二个参数传递。
Moment.js 本地化日期和时间
使用 locale 函数,我们可以设置获取输出的区域设置。
const moment = require('moment');
moment.locale('sk');
let now = moment();
console.log(now.format('LLLL'));
moment.locale('de');
now = moment();
console.log(now.format('LLLL'));
moment.locale('hu');
now = moment();
console.log(now.format('LLLL'));
在该示例中,我们以三种不同的区域设置打印当前 moment。
$ node localized.js nedeľa 1. júl 2018 22:21 Sonntag, 1. Juli 2018 22:21 2018. július 1., vasárnap 22:21
我们有当前 moment 的斯洛伐克语、德语和匈牙利语日期和时间输出。
通用时间
我们的星球是一个球体;它绕其轴旋转。 地球向东旋转,因此太阳在不同地点以不同的时间升起。 地球大约每 24 小时自转一次。 因此,世界被划分为 24 个时区。 在每个时区,都有不同的本地时间。 本地时间通常会因夏令时而进一步修改。
对于一个全球时间有实际需求。 一个全球时间有助于避免关于时区和夏令时的混淆。 UTC(协调世界时)被选为主要的时间标准。 UTC 用于航空、天气预报、飞行计划、空中交通管制许可和地图。 与当地时间不同,UTC 不会随季节变化而变化。
const moment = require('moment');
let localTime = moment();
console.log(localTime.format());
let utcTime = moment().utc();
console.log(utcTime.format('lll'));
该示例打印当前的 UTC 时间和当地时间。
let utcTime = moment().utc();
通用时间使用 utc 检索。
$ node utc.js 2018-07-01T21:15:17+02:00 Jul 1, 2018 7:15 PM
在我们的例子中,本地时间和通用时间之间的差异是两个小时。 一个小时是时区,另一个小时是夏令时。
Moment.js 闰年
闰年是包含额外一天的年份。 日历中添加额外一天的原因是天文年和日历年之间的差异。
const moment = require('moment');
// Assume year >= 1582 in the Gregorian calendar.
let years = [ 2000, 2002, 2004, 2008, 2012, 2016, 2020,
1900, 1800, 1600 ];
for (year of years) {
let ym = moment([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
来源
在本文中,我们使用 Moment.js 库在 JavaScript 中处理了日期和时间。