当前日期格式化
let curTime = moment().format('YYYY-MM-DD HH:mm:ss') console.log('当前日期时间curTime:' + curTime)//curTime:2019-01-30 10:21:11
指定日期格式化
let a = '20190130' let aFormat = moment(a).format('YYYY-MM-DD') console.log('aFormat:' + aFormat)//aFormat:2019-01-30
日期操作
//距离当前时间:七天 let sevenDaysAgo = moment().subtract(7, 'days').format('YYYY-MM-DD') console.log('sevenDaysAgo:' + sevenDaysAgo)//sevenDaysAgo:2019-01-23 //距离当前时间:一周 let oneWeekAgo = moment().subtract(1, 'weeks').format('YYYY-MM-DD') console.log('oneWeekAgo:' + oneWeekAgo)//oneWeekAgo:2019-01-23 //距离当前时间:三个月 let threeMonthsAgo = moment().subtract(3, "months").format("YYYY-MM-DD") console.log('threeMonthsAgo:' + threeMonthsAgo)//threeMonthsAgo:2018-10-30 //距离当前时间:一年 let oneYearAgo = moment().subtract(1, "years").format("YYYY-MM-DD") console.log('oneYearAgo:' + oneYearAgo)//oneYearAgo:2018-01-30 减法,对应于:subtract()方法 加法,对应于:add()方法
根据身份证号码获得周岁年龄
let idCardNumber = '234567199302019929' let birthday = idCardNumber.slice(6, 14) console.log('出生日期:' + birthday)//出生日期:19930201 console.log('当前日期:' + moment().format("YYYY-MM-DD"))//当前日期:2019-01-30 let age = moment().diff(moment(birthday), 'years') console.log('周岁年龄:' + age)//周岁年龄:25
日期与时间戳之间的转换
当涉及到日期的时间轴拖拽,那么通常需要把日期转换成时间戳来进行操作 //将日期转换成时间戳 //moment().valueOf() //new Date().getTime() //Date.parse(new Date()) let timestamp1 = moment().unix(); let timestamp2 = moment().valueOf(); let timestamp3 = new Date().getTime(); let timestamp4 = Date.parse(new Date()); //将时间戳转换成日期 moment(时间戳).format() let timestampToDate1 = moment(timestamp1).format("YYYY-MM-DD"); let timestampToDate2 = moment(timestamp2).format("YYYY-MM-DD"); let timestampToDate3 = moment(timestamp3).format("YYYY-MM-DD"); let timestampToDate4 = moment(timestamp4).format("YYYY-MM-DD"); console.log('timestamp1:' + timestamp1);//timestamp1:1550657032 console.log('timestamp2:' + timestamp2);//timestamp2:1550657032279 console.log('timestamp3:' + timestamp3);//timestamp3:1550657032279 console.log('timestamp4:' + timestamp4);//timestamp4:1550657032000 console.log('timestampToDate1:' + timestampToDate1);//timestampToDate1:1970-01-19 console.log('timestampToDate2:' + timestampToDate2);//timestampToDate2:2019-02-20 console.log('timestampToDate3:' + timestampToDate3);//timestampToDate3:2019-02-20 console.log('timestampToDate4:' + timestampToDate4);//timestampToDate4:2019-02-20
由上面的案例测试可知:
- moment().unix() 获得的时间戳单位为秒
- moment().valueOf() 等同于 new Date().getTime() 获得的时间戳单位为毫秒
- Date.parse() 得到的值是以毫秒为单位的,且后三位默认为0,即不具体到毫秒
- 如果想将时间戳转化为日期,moment的参数必须是毫秒为单位的,它就是识别为毫秒的,如果不是的话,会使结果出错