Moment.js简单使用

一、设置语言环境,如设置中文环境:

moment.locale("zh-cn");

二、当前时间、指定时间:

// 假设当前时间为: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")

三、年月日:

// 假设当前时间为: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

四、时分秒:

// 假设当前时间为: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

五、显示周几、星期几:

// 显示当前周几下标,0:周日、1:周1、2:周2、...、周六:6
moment().format("d"); // 结果:1

// 显示当前是周几,如:周1、周2、周3、...
moment().format("ddd"); // 结果:周一

// 显示当前是星期几,如:星期1、星期2、星期3、...
moment().format("dddd"); // 结果:星期三

六、显示季度:

// 假设当前时间为:2018年12月10日
 moment().format("Q"); // 结果:4

七、显示一年中的第几天:

// 假设当前时间为:2018年12月10日
 moment().format("DDD"); // 结果:344
moment().format("DDDo"); // 结果:344日
moment().format("DDDD"); // 结果:344

八、星期下标:

// 假设当前时间为:2018年12月10日

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

九、一年中第几个星期:

// 假设当前时间为: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

十、上午仍是下午:

// 假设当前时间为:2018年12月10日
 moment().format("A"); // 结果:下午
moment().format("a"); // 结果:下午

十一、时间戳、毫秒数:

// 时间戳(总秒数)
moment().format("X"); // 结果:1544425410 // 总毫秒数
moment().format("x"); // 结果:1544425410853

 十二、时间差:

// 默认时间差为毫秒
let begin = moment(); let end = moment().add(2,'second'); end.diff(begin); // 结果:2000
相关文章
相关标签/搜索