Moment.js 教程展示了如何使用 Moment.js 模块在 JavaScript 中处理日期和时间。
Moment.js
Moment.js 是一个轻量级的 JavaScript 日期库,用于解析、验证、操作和格式化日期。
在本文中,我们在 Node 应用程序中使用 Moment.js。有一个类似的 Day.js 库,在 Day.jstutorial 中有介绍。
设置 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 对象来创建矩对象。
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 对象来定义时刻对象。
$ 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}`);
该示例计算两个时刻对象在天数和小时数之间的差异。
let days = d2.diff(d1, 'days');
第二个参数表示输出将以天为单位。
$ node difference.js Difference in days: 16 Difference in hours: 384
Borodino 战役是 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 s 转换为人类可读的格式。
let unixTime = moment().unix();
我们使用unix
函数获取Unix 时间。返回值是从 Unix 纪元开始经过的秒数。
let unixTime2 = moment(1000); console.log(unixTime2.format('MM-DD-YYYY'));
我们得到 1 s 的 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'));
在示例中,我们在三个不同的语言环境中打印当前时刻。
$ 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
我们有当前时刻的斯洛伐克语、德语和匈牙利语日期和时间输出。
世界时
我们的星球是一个球体;它绕着它的轴旋转。地球向东自转,所以太阳在不同的时间在不同的地方升起。地球大约每 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 中处理日期和时间。
列出所有 JavaScript 教程。