momentJS日期处理类库---时间加减处理

xiaoxiao2025-09-03  10

计算最近在使用JavaScript计算时间差的时候,发现很多问题需要处理,在查看momentJS之后,发现非常容易。

        console.log(moment().format("YYYY-MM-DD HH:mm:ss")); //当前时间         console.log(moment().subtract(10, "days").format("YYYY-MM-DD"));    //当前时间的前10天时间         console.log(moment().subtract(1, "years").format("YYYY-MM-DD"));    //当前时间的前1年时间         console.log(moment().subtract(3, "months").format("YYYY-MM-DD"));   //当前时间的前3个月时间         console.log(moment().subtract(1, "weeks").format("YYYY-MM-DD"));    //当前时间的前一个星期时间

在实际应用中,我们经常需要计算两个时间的差值,用来确定消逝的时间,如下:

var m1 = moment('2017-12-18 10:00:20'),     m2 = moment('2017-12-18 10:10:00'),     du = moment.duration(m2 - m1, 'ms'); //  输出结果为“10 分钟” console.log(du.locale('zh-cn').humanize()) 在要求精确的环境中,比如要精确到秒,并且能提供秒递增的动画功能,此时“humanize()”就显得力不从心,但duration又没有提供moment的“format”方法,怎么办呢?

初步的想法是将moment.duration对象转换为moment对象,然后再利用“format”方法进行转换,但是结果却多了8小时,如下:

var m1 = moment('2017-12-18 10:00:20'),     m2 = moment('2017-12-18 10:10:00'),     du = moment(m2 - m1).format('HH时mm分ss秒'); //  输出结果为08时09分40秒 console.log(du);

8小时,很容易就让我们想到是时区的问题,可以通过如下方式进行验证:

 

du = moment(m2 - m1).format('HH时mm分ss秒 ZZ'); //  输出结果为08时09分40秒 +0800 console.log(du)

粗暴的方式是直接减去8小时的数据,优雅的方式是引入Moment Timezone,如下:

//  Africa/Abidjan为+00:00时区 //  输出结果00时09分40秒 du = moment.tz(m2 - m1, "Africa/Abidjan").format('HH时mm分ss秒')  

http://momentjs.cn/   中文网

转载请注明原文地址: https://www.6miu.com/read-5035652.html

最新回复(0)