moment.js学习总结
一、 介绍:
moment.js不依赖任何第三方库,支持字符串、Date、时间戳以及数组等格式,可以像PHP的date()函数一样,格式化日期时间,计算相对时间,获取特定时间后的日期时间等等。下面是一些使用例子。
二、创建时间
moment() // Mon May 07 2018 16:30:44 GMT+0800 moment("1995-12-25") // Mon Dec 25 1995 00:00:00 GMT+0800 moment("12-25-1995", "MM-DD-YYYY") // 1995-12-25 moment({ year :2010, month :3, day :5, hour :15, minute :10, second :3, millisecond :123}) moment(Date.now() - 24 * 60 * 60 * 1000) // 昨天 Sun May 06 2018 16:35:41 GMT+0800 moment(new Date(2011, 9, 16)) // 2011-10-16
三、格式化时间 format方法
moment().format('MMMM Do YYYY, h:mm:ss a'); // March 20th 2017, 11:52:12 am
moment().format('dddd'); // Monday
moment().format("MMM Do YY"); // Mar 20th 17
moment().format('YYYY [escaped] YYYY'); // 2017 escaped 2017
moment().format(); // 2017-03-20T11:52:12+08:0
moment().format('YYYY年MM月DD日 HH:mm:ss') //2018年05月07日 16:40:54
四、多样化的本地时间支持
moment.locale(); // zh-cn moment().format('LT'); // 11:55 moment().format('LTS'); // 11:55:16 moment().format('L'); // 2017年3月20日 moment().format('l'); // 2017年3月20日 moment().format('LL'); // 2017年3月20日 moment().format('ll'); // 2017年3月20日 moment().format('LLL'); // 2017年3月20日中午11点55分 moment().format('lll'); // 2017年3月20日 11:55 moment().format('LLLL'); // 2017年3月20日星期一中午11点55分 moment().format('llll'); // 2017年3月20日星期一 11:55
五、操作
moment().add(7, 'days') // 之后的第7天。第2个参数还可以是 'months', 'years' 等。注意是复数。 moment().add(7, 'd')// 与上面一行代码的运行结果一样。 moment().subtract(1, 'months') // 上个月 moment().startOf('week') // 这周的第一天 moment().startOf('hour') // 等效与 moment().minutes(0).seconds(0).milliseconds(0)。 // 还支持 'year','month' 等 moment().endOf('week')
六、查询验证
// 早于 moment('2010-10-20').isBefore('2010-10-21') // true moment('2010-10-20').isBefore('2010-12-31', 'year') // false moment('2010-10-20').isBefore('2011-01-01', 'year') // true // 是否相等 moment('2010-10-20').isSame('2010-10-20') // true moment('2010-10-20').isSame('2009-12-31', 'year') // false moment('2010-10-20').isSame('2010-01-01', 'year') // true // 晚于 moment('2010-10-20').isAfter('2010-10-19') // true moment('2010-10-20').isAfter('2010-01-01', 'year') // false moment('2010-10-20').isAfter('2009-12-31', 'year') // true // 是否在时间范围内 moment('2010-10-20').isBetween('2010-10-19', '2010-10-25') // true 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 moment().isLeapYear() // 是否是闰年
七、dome
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dome</title>
</head>
<body>
<div id="time"></div>
</body>
<script src="./moment.js"></script>
<script>
document.getElementById("time").innerHTML = moment().format('YYYY年MM月DD日 HH:mm:ss');
</script>
</html>
参考资料:
1.moment.js--时间格式化处理利器
2.Moment.js 写法示例
3.moment.js中文网

浙公网安备 33010602011771号