Moment.js簡單使用


1、設置語言環境,如設置中文環境:

moment.locale("zh-cn");

2、當前時間、指定時間:

// 假設當前時間為:2018年12月10日

moment(); // 結果:moment("2018-12-10T14:25:00.463")
moment(new Date()); // 結果:moment("2018-12-10T14:25:00.463")

moment("2018-12-10 13:48:36.458"); // 結果:moment("2018-12-10T13:48:36.458")

3、年月日:

// 假設當前時間為:2018年12月10日

//
moment().format("YY");  // 結果:18
moment().format("YYYY"); // 結果:2018
moment().format("gg"); // 結果:18
moment().format("gggg"); // 結果:2018
moment().format("GG"); // 結果:18
moment().format("GGGG"); // 結果:2018

//
moment().format("M"); // 結果:12
moment().format("MM"); // 結果:12
moment().format("Mo"); // 結果:12月
moment().format("MMM"); // 結果:12月
moment().format("MMMM"); // 結果:十二月

//
moment().format("D"); // 結果:10
moment().format("Do"); // 結果:10日
moment().format("DD"); // 結果:10

4、時分秒:

// 假設當前時間為:2018年12月10日

// 12小時制
moment().format("h"); // 結果:2
moment().format("hh"); // 結果:02
// 24小時制
moment().format("H"); // 結果:14
moment().format("HH"); // 結果:14

//
moment().format("m"); // 結果:55
moment().format("mm"); // 結果:55

//
moment().format("s"); // 結果:5
moment().format("ss"); // 結果:05

// 毫秒
moment().format("S"); // 結果:8
moment().format("SS"); // 結果:87
moment().format("SSS"); // 結果:876

5、顯示周幾、星期幾:

// 顯示當前周幾下標,0:周日、1:周一、2:周二、...、周六:6
moment().format("d"); // 結果:1

// 顯示當前是周幾,如:周一、周二、周三、...
moment().format("ddd"); // 結果:周一

// 顯示當前是星期幾,如:星期一、星期二、星期三、...
moment().format("dddd"); // 結果:星期三

6、顯示季度:

// 假設當前時間為:2018年12月10日

moment().format("Q"); // 結果:4

7、顯示一年中的第幾天:

// 假設當前時間為:2018年12月10日

moment().format("DDD"); // 結果:344
moment().format("DDDo"); // 結果:344日
moment().format("DDDD"); // 結果:344

8、星期下標:

// 假設當前時間為:2018年12月10日

// Locale:0 1 ... 5 6
moment().format("e"); // 結果:0
// ISO:1 2 ... 6 7
moment().format("E"); // 結果:1

9、一年中第幾個星期:

// 假設當前時間為:2018年12月10日

moment().format("w"); // 結果:50
moment().format("wo"); // 結果:50周
moment().format("ww"); // 結果:50

moment().format("W"); // 結果:50
moment().format("Wo"); // 結果:50周
moment().format("WW"); // 結果:50

10、上午還是下午:

// 假設當前時間為:2018年12月10日

moment().format("A"); // 結果:下午
moment().format("a"); // 結果:下午

11、時間戳、毫秒數:

// 時間戳(總秒數)
moment().format("X"); // 結果:1544425410
// 總毫秒數
moment().format("x"); // 結果:1544425410853

 12、時間差:

// 默認時間差為毫秒
let begin = moment();
let end = moment().add(2,'second');
end.diff(begin); // 結果:2000

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM