一、安裝 / 使用
npm install moment
注:使用版本為 2.22.2
var moment = require('moment');
moment().format(); // 2018-09-11T11:34:13+08:00
moment 時間格式對照表
| Key | Key_2 | Shorthand |
|---|---|---|
| years | year | y |
| quarters | quarter | Q |
| months | month | M |
| weeks | week | w |
| days | day | d |
| hours | hour | h |
| minutes | minute | m |
| seconds | second | s |
| milliseconds | millisecond | ms |
二、解析
1、當前時間
moment() //帶時區
moment().utc() //不帶時區
2、字符串
moment(String, String, String, Boolean);
or
moment(String, String[], String, Boolean);
(1)第一個參數:ISO 8601 支持的字符串格式
moment("2013-02-08 09:30:26.123+07:00")
//or +'T'
moment("2013-02-08T09:30:26.123+07:00")
(2)第二個參數:moment 支持的字符串格式
詳細格式看文檔
moment("12-25-1995", "MM-DD-YYYY");
// 如果您不知道輸入字符串的確切格式,但知道它可能是眾多格式之一,則可以使用格式數組。
moment("12-25-1995", ["MM-DD-YYYY", "YYYY-MM-DD"]);
(3)第三個參數:指定 時區
moment('2012 juillet', 'YYYY MMM', 'fr');
(4)第四個參數:開啟 嚴格模式
嚴格的解析要求格式和輸入完全匹配。
3、對象
moment({ y :2010, M :3, d :5, h :15, m :10, s :3, ms :123});
moment({ year :2010, month :3, day :5, hour :15, minute :10, second :3, millisecond :123});
moment({ years:2010, months:3, days:5, hours:15, minutes:10, seconds:3, milliseconds:123});
moment({ years:2010, months:3, date:5, hours:15, minutes:10, seconds:3, milliseconds:123});
moment({ hour:15, minute:10 });
4、Unix Timestamp (seconds / milliseconds)
moment.unix(1318781876); //10位 精確到秒
moment(1318781876406); //13位 精確到毫秒
注:推薦個 UNIX 時間轉化工具:http://tool.chinaz.com/Tools/unixtime.aspx
5、JS 的 DATE 對象
moment(new Date(2011, 9, 16));
6、克隆
var a = moment();
// 方法一
var b = moment(a);
// 方法二
var b = a.clone();
問:如何判斷解析是否正確?
isValid() 、invalidAt()
var m = moment("2011-10-10T10:20:90");
m.isValid(); // false
//您可以使用 invalidAt() 確定哪個日期單位溢出。
m.invalidAt(); // 5 for seconds
三、取值 / 賦值
1、普通方法
毫秒
//存
moment().millisecond(Number);
//取
moment().millisecond(); // Number
//存
moment().milliseconds(Number);
//取
moment().milliseconds(); // Number
接受0到999之間的數字。如果超出范圍,它將冒泡到秒。
秒
moment().second(Number);
moment().second(); // Number
moment().seconds(Number);
moment().seconds(); // Number
接受0到59之間的數字。如果超出范圍,它將冒泡到分鍾。
分鍾
moment().minute(Number);
moment().minute(); // Number
moment().minutes(Number);
moment().minutes(); // Number
接受從0到59的數字。如果超出范圍,它將冒泡到小時
小時
moment().hour(Number);
moment().hour(); // Number
moment().hours(Number);
moment().hours(); // Number
接受0到23之間的數字。如果超出范圍,它將會冒泡到當天。
日 of 月
moment().date(Number);
moment().date(); // Number
moment().dates(Number);
moment().dates(); // Number
接受從1到31的數字。如果超出范圍,它將冒泡到幾個月。
日 of 年
moment().dayOfYear(Number);
moment().dayOfYear(); // Number
接受從1到366的數字。如果超出范圍,它將冒泡到多年。
星期
moment().day(Number|String);
moment().day(); // Number
moment().days(Number|String);
moment().days(); // Number
接受數字 | 字符串。星期日為0,星期六為6 | 星期日為Sunday,星期六為Saturday
星期(ISO)
moment().isoWeekday(Number);
moment().isoWeekday(); // Number
接受數字。星期一為1,星期日為7
星期(區域標准)
moment().weekday(Number);
moment().weekday(); // Number
按照區域設置(下面會有介紹)來定:
如果區域設置將星期一指定為一周的第一天,那moment().weekday(0)將是星期一。
如果區域設置將星期日指定為一周的第一天,那moment().weekday(0)將是星期天。
周 of 年(區域標准)
moment().week(Number);
moment().week(); // Number
moment().weeks(Number);
moment().weeks(); // Number
獲取或設置一年中的一周。
按照區域設置(下面會有介紹)來定:
一年中的一周取決於哪一天是一周的第一天(星期日,星期一等),以及哪一周是一年中的第一周。
例如,在美國,星期日是一周的第一天。1月1日這一周是一年中的第一周;在法國,星期一是一周的第一天,而1月4日的星期是一年的第一周。
周 of 年(ISO)
moment().isoWeek(Number);
moment().isoWeek(); // Number
moment().isoWeeks(Number);
moment().isoWeeks(); // Number
獲取或設置年份的 ISO 周。
查看一年有多少周數
moment().weeksInYear();
根據當前時刻的區域設置獲取周數。(只可 get 不可 set)
查看一年有多少周數 (ISO)
moment().isoWeeksInYear();
根據 ISO 周,獲取當前時刻的周數。(只可 get 不可 set)
月
moment().month(Number|String);
moment().month(); // Number
moment().months(Number|String);
moment().months(); // Number
接受數字 | 字符串。一月為0,十二月為11 | 一月為January,十二月為December
季度
moment().quarter(); // Number
moment().quarter(Number);
接受從1到4的數字。
年
moment().year(Number);
moment().year(); // Number
moment().years(Number);
moment().years(); // Number
獲取或設置年份。接受 -270,000 至 270,000 的數字。
年 by 周(區域標准)
moment().weekYear(Number);
moment().weekYear(); // Number
根據區域設置獲取或設置周年。
按照區域設置(下面會有介紹)來定:
例如,在美國,包含1月1日的一周始終是第一周。在美國,周也將在周日開始。如果1月1日是星期一,則12月31日將屬於與1月1日相同的一周,因此與1月1日相同的周年。12月30日將與12月31日的周年不同(相差一年)。
年 by 周(ISO)
moment().isoWeekYear(Number);
moment().isoWeekYear(); // Number
獲取或設置 ISO 周年。
2、get / set 方法
取值
moment().get('year');
moment().get('month'); // 0 to 11
moment().get('date');
moment().get('hour');
moment().get('minute');
moment().get('second');
moment().get('millisecond');
賦值
moment().set('year', 2013);
moment().set('month', 3); // April
moment().set('date', 1);
moment().set('hour', 13);
moment().set('minute', 20);
moment().set('second', 30);
moment().set('millisecond', 123);
//同時設置多個
moment().set({'year': 2013, 'month': 3});
最大 / 小值
moment.max(Moment[,Moment...]);
or
moment.min(Moment[,Moment...]);
var a = moment().subtract(1, 'day');
var b = moment().add(1, 'day');
moment.max(a, b); // b
moment.min(a, b); // a
四、操作
moment 支持流暢的 鏈式操作,如:
moment().add(7, 'days').subtract(1, 'months').year(2009).hours(0).minutes(0).seconds(0);
1、加減法
add() / subtract()
moment().add(7, 'days');
moment().add(7, 'days').add(1, 'months'); // with chaining
moment().add({days:7,months:1}); // with object literal
moment().add(moment.duration({'days' : 1});); // with add duration
//特殊情況
moment([2010, 0, 31]).add(1, 'months'); // February 28
2、取 開始時間 / 結束時間
startOf() / endOf()
moment().startOf('year'); // set to January 1st, 12:00 am this year
moment().startOf('month'); // set to the first of this month, 12:00 am
moment().startOf('quarter'); // set to the beginning of the current quarter, 1st day of months, 12:00 am
moment().startOf('week'); // set to the first day of this week, 12:00 am
moment().startOf('isoWeek'); // set to the first day of this week according to ISO 8601, 12:00 am
moment().startOf('day'); // set to 12:00 am today
moment().startOf('hour'); // set to now, but with 0 mins, 0 secs, and 0 ms
moment().startOf('minute'); // set to now, but with 0 seconds and 0 milliseconds
moment().startOf('second'); // same as moment().milliseconds(0);
五、時區
1、修改全局時區
看我另一篇: 《從 moment -> nodejs -> sequelize -> postgres,你都得設置好時區》
2、修改具體時間的時區
utc()、local()、utcOffset()
var a = moment();
console.log(a.format()); // 2018-09-12T00:16:18+08:00
a.utc(); //變成 utc 時區
console.log(a.format()); // 2018-09-11T16:16:18Z
a.local(); //變成 本地 時區
console.log(a.format()); // 2018-09-12T00:16:18+08:00
a.utcOffset(4); //變成 自定義 時區
console.log(a.format()); // 2018-09-11T20:16:18+04:00
問:
local()是怎么知道你所在的時區是東八區呢?答:Moment 也是通過 javascript 的 Date.getTimezoneOffset() 獲取到操作系統時區的,而操作系統的時區可以這樣修改(以 mac 為例):
3、 utcOffset() 詳解
utcOffset() 的單位是分鍾
// getter
console.log(moment().utcOffset()); //480
// setter(以下兩種方式結果一樣)
moment().utcOffset(480);
// 如果輸入小於16或大於-16,則會將輸入解釋為小時。
moment().utcOffset(8);
4、Moment Timezone 庫
修改時區時如果不想輸入數字而是地域字符串,請添加 Moment Timezone 並使用 .tz():
moment(1369266934311).tz('Asia/Shanghai')
六、顯示
1、格式化
format()
// 默認為 `moment.defaultFormat`,即 ISO8601格式 `YYYY-MM-DDTHH:mm:ssZ`
moment().format(); // "2014-09-08T08:02:17-05:00" (ISO 8601)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
// [] 用來插入自定義字符串
moment().format('[today] dddd'); // 'today Sunday'
我常用的格式為YYYY-MM-DD HH:mm:ss,其他的格式的看文檔。
2、時間差距
(1)人性化展示
時差(之前):fromNow() / from()
時差(之后):toNow() / to()
參數傳 true 會簡練顯示:
//fromNow()
moment([2007, 0, 29]).fromNow(); // 4 years ago
moment([2007, 0, 29]).fromNow(true); // 4 years
//from()
moment([2007, 0, 10]).from(moment([2007, 0, 5])); // "in 5 days"
moment([2007, 0, 10]).from(moment([2007, 0, 5]), true); // "5 days"
//toNow()
moment([2007, 0, 29]).toNow(); // in 4 years
moment([2007, 0, 29]).toNow(true); // 4 years
//to()
moment([2007, 0, 10]).to(moment([2007, 0, 5])); // "5 days ago"
moment([2007, 0, 10]).to(moment([2007, 0, 5]), true); // "5 days"
注:不要通過 a.from(moment()) 去取代 a.fromNow() , 因為獲取當前日期會有誤差。
時差(之前)規則參考表:
| Range | Key | Sample Output |
|---|---|---|
| 0 to 45 seconds | s | a few seconds ago |
| 45 to 90 seconds | m | a minute ago |
| 90 seconds to 45 minutes | mm | 2 minutes ago ... 45 minutes ago |
| 45 to 90 minutes | h | an hour ago |
| 90 minutes to 22 hours | hh | 2 hours ago ... 22 hours ago |
| 22 to 36 hours | d | a day ago |
| 36 hours to 25 days | dd | 2 days ago ... 25 days ago |
| 25 to 45 days | M | a month ago |
| 45 to 345 days | MM | 2 months ago ... 11 months ago |
| 345 to 545 days (1.5 years) | y | a year ago |
| 546 days+ | yy | 2 years ago ... 20 years ago |
時差(之后)規則參考表:
| Range | Key | Sample Output |
|---|---|---|
| 0 to 45 seconds | s | in seconds |
| 45 to 90 seconds | m | in a minute |
| 90 seconds to 45 minutes | mm | in 2 minutes ... in 45 minutes |
| 45 to 90 minutes | h | in an hour |
| 90 minutes to 22 hours | hh | in 2 hours ... in 22 hours |
| 22 to 36 hours | d | in a day |
| 36 hours to 25 days | dd | in 2 days ... in 25 days |
| 25 to 45 days | M | in a month |
| 45 to 345 days | MM | in 2 months ... in 11 months |
| 345 to 547 days (1.5 years) | y | in a year |
| 548 days+ | yy | in 2 years ... in 20 years |
(2)毫秒展示
diff()
var a = moment([2008, 6]);
var b = moment([2007, 0]);
a.diff(b, 'years'); // 1
//對比精度提高
a.diff(b, 'years', true); // 1.5
b.diff(a, 'years', true); // -1.5
注:diff() 會有一些特殊的處理月和年差異。它經過優化,可確保相同日期的兩個月始終是一個整數。
所以1月15日到2月15日應該是1個月。 2月28日至3月28日應該是1個月。 2011年2月28日至2012年2月28日應該是1年。
(3)日歷形式展示
moment().calendar(referenceTime, formats);
| 情況 | 顯示 |
|---|---|
| Last week | Last Monday at 2:30 AM |
| The day before | Yesterday at 2:30 AM |
| The same day | Today at 2:30 AM |
| The next day | Tomorrow at 2:30 AM |
| The next week | Sunday at 2:30 AM |
| Everything else | 7/10/2011 |
moment("2018-09-02 12:12:12").calendar("2018-09-01 01:01:01");
//"Tomorrow at 12:12 PM"
moment("2018-09-02 12:12:12").calendar("2018-09-01 01:01:01", {
sameDay: '[Today]',
nextDay: '[明天]HH[點]', // focus here
nextWeek: 'dddd',
lastDay: '[Yesterday]',
lastWeek: '[Last] dddd',
sameElse: 'DD/MM/YYYY'
});
//"明天12點"
3、獲取當月的天數
daysInMonth()
4、Unix 時間戳(秒 / 毫秒)
unix() / valueOf()
5、獲取 JS 的 DATE 對象
toDate()
6、獲取數組
toArray()
moment().toArray(); // [2013, 1, 4, 14, 40, 16, 154];
7、獲取對象
toObject()
moment().toObject() // {
// years: 2015
// months: 6
// date: 26,
// hours: 1,
// minutes: 53,
// seconds: 14,
// milliseconds: 600
// }
七、查詢
1、時間先后比較
(1)是否之前 / 之后 / 相同
isBefore / isAfter / isSame
moment('2010-10-20').isBefore('2010-10-21'); // true
// 第二個參數決定精度
moment('2010-10-20').isBefore('2010-10-21', 'year'); // false
(2)是否之間 —— isBetween
遵循左開右開原則
moment('2010-10-20').isBetween('2010-01-01', '2012-01-01', 'year'); // false
moment('2010-10-20').isBetween('2009-12-31', '2012-01-01', 'year'); // true
2、是否是閏年
isLeapYear
3、是否是 moment 對象 / 是否是 Date 對象
isMoment / isDate
八、國際化
您可以加載多個區域設置並在它們之間輕松切換。
1、切換區域設置
(1)全局
moment.locale(xxx)
xxx 支持的區域可以看 node_modules/moment/locale/ 下的文件名
// /app.js
moment.locale('fr');
moment(1316116057189).fromNow() // il y a une heure
// /router/index.js
moment.locale('en');
moment(1316116057189).fromNow() // an hour ago
建議如下切換方式,可以判斷是否切換成功:
if (moment.locale('fr') === 'fr'){
console.log("success");
} else {
console.log("fail");
}
更改后不會影響原有實例:
moment.locale('fr');
var m = moment(1316116057189);
m.fromNow(); // il y a une heure
moment.locale('en');
m.fromNow(); // il y a une heure
moment(1316116057189).fromNow(); // an hour ago
支持模糊匹配,例如在瀏覽器中執行 window.navigator.language 返回 en-NZ,則會正確的識別為 en
moment.locale('en-NZ'); // 'en'
(2)局部
var fr = moment().locale('fr');
fr.localeData().months(moment([2012, 0])) // "janvier"
fr.locale('en');
fr.localeData().months(moment([2012, 0])) // "January"
2、獲取當前區域設置
(1)全局
moment.locale(); // returns 'en'
(2)局部
moment().locale(); // returns 'en'
3、獲取 月份和星期 枚舉列表
moment.months()
moment.monthsShort()
moment.weekdays()
moment.weekdaysShort()
moment.weekdaysMin()
moment.months()
/*[ 'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December' ]*/
moment.weekdays(3); // 'Wednesday'
4、獲取區域設置的詳細信息:
localeData()
localeData = moment.localeData()
// or
localeData = moment.localeData('fr')
//詳細信息
localeData.months()
localeData.monthsShort()
localeData.monthsParse()
localeData.weekdays()
localeData.weekdaysShort()
localeData.weekdaysMin()
localeData.weekdaysParse()
localeData.longDateFormat()
localeData.isPM()
localeData.meridiem()
localeData.calendar()
localeData.relativeTime()
localeData.pastFuture()
localeData.ordinal()
localeData.preparse()
localeData.postformat()
localeData.weeks()
localeData.invalidDate()
localeData.firstDayOfWeek()
localeData.firstDayOfYear()
5、自定義區域設置
locale(string, object)
moment.locale('en-my-settings', {
// customizations.
});
注:詳細的自定義配置見文檔
也可以覆蓋已有語言環境。
moment.locale('en', {
// customizations
});
還可以刪除已有的語言環境
moment.locale('fr', null);
moment.locale('fr'); // 'en'
九、時間段
時間段在概念上更類似於 '2 小時'而不是'今天下午 2 點到 4 點'。因此,它們不是在依賴於上下文的單元之間進行轉換的良好解決方案。
1、創建
moment.duration(Number);
moment.duration(Number, String);
moment.duration(Object);
moment.duration(String);
moment.duration(100); // 100 milliseconds
moment.duration(2, 'seconds');
moment.duration(2, 'minutes');
moment.duration(2, 'hours');
moment.duration(2, 'days');
moment.duration(2, 'weeks');
moment.duration(2, 'months');
moment.duration(2, 'years');
moment.duration({
seconds: 2,
minutes: 2,
hours: 2,
days: 2,
weeks: 2,
months: 2,
years: 2
});
2、擬人化 輸出
moment.duration(1, "minutes").humanize(); // a minute
// 詳細點
moment.duration(1, "minutes").humanize(true); // in a minute
3、量化輸出
milliseconds() vs asMilliseconds()
// 計算零頭
moment.duration(500).milliseconds(); // 500
moment.duration(1500).milliseconds(); // 500
moment.duration(15000).milliseconds(); // 0
// 計算累計
moment.duration(500).asMilliseconds(); // 500
moment.duration(1500).asMilliseconds(); // 1500
moment.duration(15000).asMilliseconds(); // 15000
seconds / asSeconds
minutes / asMinutes
hours / asHours
days / asDays
months / asMonths
years / asYears
注:還有另一種寫法:
duration.get('hours')= duration.hours
duration.as('hours')= duration.asHours
4、加減法
add() / subtract()
var a = moment.duration(1, 'd');
var b = moment.duration(2, 'd');
a.add(b).days(); // 3
5、判斷是否是時間段
isDuration()
參考資料
官方文檔:
http://momentjs.cn/docs/#/displaying/
http://momentjs.cn/timezone/docs/

