Moment.js 教程展示了如何通过 Moment.js 模块在 JavaScript 中使用日期和时间。
Moment.js
Moment.js 是一个轻量级的 JavaScript 日期库,用于解析,验证,操作和格式化日期。
在本教程中,我们在 Node 应用中使用 Moment.js。 Day.js 教程中介绍了类似的 Day.js 库。
安装 Moment.js
首先,我们安装 Moment.js。
$ nodejs -vv9.11.2
我们使用 Node 版本 9.11.2。
$ npm init
我们启动一个新的 Node 应用。
$ npm i moment
我们使用npm i moment命令安装 Moment.js。
Moment.js 今天的日期
在第一个示例中,我们使用 Moment.js 获取今天的日期。
today.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.js2018-07-01T16:32:53+02:00
这是 ISO 标准格式。 日期和时间部分用 T 字符分隔。 该字符串以时区结尾。
创建 Moment.js 对象
我们可以使用几种方法来创建日期和时间 Moment.js 对象。 这些对象必须稍后再格式化为人类可读的格式。
create_objects.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");
我们从字符串创建一个矩对象。
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'));
我们可以使用 JSON 对象创建力矩对象。
let d4 = moment(1530471537000);console.log(d4.format('ll'));
我们使用 unix 时间戳(以毫秒为单位)定义矩对象。
let d5 = moment(new Date(2011, 11, 22));console.log(d5.format('ll'));
最后,我们使用 JavaScript 内置的 Date 对象定义一个矩对象。
$ node create_moment_objects.jsJun 3, 2018Dec 23, 2017Apr 5, 2010Jul 1, 2018Dec 22, 2011
这是输出。
Moment.js 格式化日期时间
Moment.js 对象使用format()函数格式化。 也有本地化格式的选项。
format.js
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.jsISO2018-07-03T10:09:47+02:00Time10:09:4710:09:47 amDateTuesday, July 3rd 20182018-07-03Localized10:09 AM10:09:47 AM10:09:47 AM07/03/20187/3/2018
这是一个示例输出。
Moment.js 计算日期时间差
使用diff()函数,我们可以计算两个日期时间对象之间的差。
difference.js
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.jsDifference in days: 16Difference in hours: 384
这是输出。
Borodino 战役是 1812 年 9 月 7 日在法国入侵俄罗斯期间的拿破仑战争中进行的战斗。
borodino.js
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.jsOn Jul 3, 2018, 75174 days have passed since the Borodino battle.
这是一个示例输出。
Moment.js 日期时间算法
add()函数用于将日期和时间添加到矩对象,而subtract()函数用于从矩对象减去日期和时间。
add_sub.js
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.jsNow: Jul 1, 2018Adding three days: Jul 4, 2018Subtracting 2 years: Jul 4, 2016
这是输出。
Moment.js 日期时间部分
在下面的示例中,我们获取了当前日期时间的部分。
parts.js
const moment = require('moment');let now = moment();let year = now.get('year');let month = now.get('month'); // 0 to 11let 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.jsYear: 2018Month: 6Date: 2Hour: 18Minute: 10Second: 3Millisecond: 329
这是一个示例输出。
Moment.js 星期,月,年
下面的示例计算星期几,月份和年份。
dayof.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.jsDay of week: 1Day of month: 2Day of year: 183
这是一个示例输出。
Moment.js 一年中的第几周,季度中的第几周
在下面的示例中,我们获得一年中的星期,一年中的季度以及一年中的星期数。
weeks_quarter.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.jsWeek of year: 27Quarter of year: 3Weeks in year: 52
这是一个示例输出。
Moment.js 相对日期时间
我们可以使用fromNow(),startOf()和endOf()函数计算相对日期时间。
relative_time.js
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.js182 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()方法检查日期和时间对象是否有效。
validity.js
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()函数可用于确定某个日期是在另一个日期之前还是之后。
date_queries.js
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.jsMay 19, 2018 is before May 20, 2018May 20, 2018 is before May 22, 2018
这是输出。
isBetween()函数检查日期是否在给定的日期范围内。
between.js
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 秒以来的秒数。
unixtime.js
const moment = require('moment');let unixTime = moment().unix();console.log(unixTime);let unixTime2 = moment(1000);console.log(unixTime2.format('MM-DD-YYYY'));
在该示例中,我们获得了当前的 unix 时间并将 unix 时间 1s 转换为人类可读的格式。
let unixTime = moment().unix();
我们通过unix()函数获得 Unix 时间。 返回的值是从 Unix 纪元开始起经过的秒数。
let unixTime2 = moment(1000);console.log(unixTime2.format('MM-DD-YYYY'));
我们得到 1 秒的 unix 时间,并以给定的格式输出。
$ node unixtime.js153060613401-01-1970
这是输出。
Moment.js 解析日期和时间
通过将日期和时间格式传递给moment()函数,我们可以解析日期和时间的字符串表示形式。
parse.js
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()函数,我们可以设置获取输出的语言环境。
localized.js
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.jsnedeľa 1\. júl 2018 22:21Sonntag, 1\. Juli 2018 22:212018\. július 1., vasárnap 22:21
我们提供了当前时刻的斯洛伐克,德国和匈牙利日期和时间输出。
世界时间
我们的星球是一个球体; 它绕其轴旋转。 地球向东旋转,因此太阳在不同位置的不同时间升起。 地球大约每 24 小时旋转一次。 因此,世界被划分为 24 个时区。 在每个时区,都有一个不同的本地时间。 夏令时通常会进一步修改此本地时间。
实际需要一个全球时间。 全球时间可以避免时区和夏令时的混淆。 UTC(世界标准时间)被选为主要时间标准。 UTC 用于航空,天气预报,飞行计划,空中交通管制通关和地图。 与当地时间不同,UTC 不会随季节变化而变化。
utc.js
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.js2018-07-01T21:15:17+02:00Jul 1, 2018 7:15 PM
在我们的案例中,本地时间与世界时间之间的时差为两个小时。 时区一个小时,夏时制另一个小时。
Moment.js 闰年
闰年是包含另一天的一年。 日历中额外一天的原因是天文日历年与日历年之间的差异。
leap_year.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.js2000 is a leap year2002 is not a leap year2004 is a leap year2008 is a leap year2012 is a leap year2016 is a leap year2020 is a leap year1900 is not a leap year1800 is not a leap year1600 is a leap year
这是输出。
在本教程中,我们使用Moment.js库在 JavaScript 中使用日期和时间。
您可能也对以下相关教程感兴趣: Day.js 教程,或列出所有 JavaScript 教程。
