平常偶尔使用,特此记录
日期格式化
moment().format('MMMM Do YYYY, h:mm:ss a'); // 七月 2日 2020, 11:14:42 上午
moment().format('dddd'); // 星期四
moment().format("MMM Do YY"); // 7月 2日 20
moment().format('YYYY [escaped] YYYY'); // 2020 escaped 2020
moment().format(); // 2020-07-02T11:14:42+08:00
//直接运行格式化的实时的日期
相对时间
moment("20111031", "YYYYMMDD").fromNow(); // 9 年前
moment("20120620", "YYYYMMDD").fromNow(); // 8 年前
moment().startOf('day').fromNow(); // 11 小时前
moment().endOf('day').fromNow(); // 13 小时内
moment().startOf('hour').fromNow(); // 15 分钟前
//与实时时间相对
实例
标准时间
new Date()
//Thu Jul 02 2020 11:31:51 GMT+0800 (中国标准时间)
格式化时间
如:日期
let str = '2003-06-15T16:00:00.000Z'
let str = '2014-07-14'
1:都先需要把日期转换成标准时间
let standardTime = moment(new Date(str)) //转为标准时间
2:再格式化成需要的
standardTime.format('YYYY-MM-DD') // 2003-06-16
standardTime.format('YYYY年MM月DD日') // 2003年06月16日
可简写为
moment(new Date(str)).format('YYYY-MM-DD')
转时间戳
moment(str).unix()*1000 //1405440000000
moment('2014-7-16').unix()*1000 //1405440000000
moment('2014-07-16').unix()*1000 //1405440000000
moment('2014.7.16').unix()*1000 //1405440000000
moment('Wed Jul 16 2014 08:00:00 GMT+0800 (中国标准时间)').unix()*1000 //1405468800
moment('2014-07-16T16:00:00.000Z').unix() //1405526400000
moment('2014--7--16').unix()*1000 //NaN
moment('2014年7月16号').unix()*1000 //NaN
moment('2014年7月16号').unix()*1000 //NaN
格式化时间戳
标准时间戳是以1970年为标准的,13位
let timestamp = 1405440000000
先将时间戳转为标准时间
let standardTime = moment(new Date(timestamp)) //Wed Jul 16 2014 00:00:00 GMT+0800 (中国标准时间)
格式化
standardTime.format("YYYYMMDD") // 20140716
简写:
moment(new Date(timestamp)).format("YYYYMMDD")