Moment.js教程展示了如何使用Moment.js模块在JavaScript中处理日期和时间。
Moment.js 是一个轻量级的JavaScript日期库,用于解析、验证、操作和格式化日期。
在本教程中,我们在一个Node应用程序中使用Moment.js。有一个类似的Day.js库,这在 Day.js tutorial 中有所涉及。
首先,我们安装Moment.js。
$ nodejs -v v9.11.2
我们使用Node 9.11.2版本。
$ npm init
我们启动一个新的Node应用。
$ npm i moment
我们用 npm i moment
命令安装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对象。这些对象以后必须被格式化为人类可读的格式。
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.js Jun 3, 2018 Dec 23, 2017 Apr 5, 2010 Jul 1, 2018 Dec 22, 2011
这是输出
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
这是一个样本输出。
通过 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
这是输出
博罗季诺战役是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.
这是一个输出示例。
add()
函数用于向时刻对象添加日期和时间, subtract()
函数用于从时刻对象中减去日期和时间。
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
这是输出
在下面的例子中,我们得到当前日期时间的部分。
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
这是一个输出样本。
下面的例子计算星期几、月份和年份。
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
这是一个输出样本。
在下面的例子中,我们得到一年中的一周,一年中的一季度,以及一年中的周数。
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
这是一个样本输出。
我们可以用 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.
这是输出
我们可以使用 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"); }
这个例子检查两天的有效性。
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()
函数来确定一个日期是否在指定的日期范围内。
Unix time 是自Unix epoch以来的秒数。 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时间1s转换**类可读的格式。
let unixTime = moment().unix();
我们用 unix()
函数得到Unix时间。返回值为从Unix Epoch开始所经过的秒数。
let unixTime2 = moment(1000); console.log(unixTime2.format('MM-DD-YYYY'));
我们得到1s的unix时间,并以给定的格式输出。
$ node unixtime.js 1530606134 01-01-1970
这是输出
我们可以通过向 moment()
函数传递日期和时间格式来解析日期和时间的字符串表示。
const moment = require('moment'); let day = "03/04/2008"; let parsed = moment(day, "DD/MM/YYYY"); console.log(parsed.format('ll'));
在这个例子中,我们解析了一个非标准的日期和时间字符串。我们将预期的格式作为 moment()
函数的第二个参数传递。
通过 locale()
函数,我们可以设置获得输出的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
在我们的例子中,当地时间和世界时间之间的差异是两个小时。一个小时是针对时区的,另一个小时是针对夏令时的。
闰年是指含有额外一天的年份。在日历中多出一天的原因是天文年和日历年之间的差异。
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中处理了日期和时间。