简体   繁体   中英

How to transfer seconds to Time format (YYYY:MM:DD HH:mm:ss) using moment.js

At first.

I using moment.js to get the diff time between two 'moment.js objects'.

from is the beginning time ; to is beginning time add the milliseconds.

Variables

var from = moment().format('YYYY-MM-DD HH:mm:ss');
var to   = moment().milliseconds(ms).format('YYYY-MM-DD HH:mm:ss');

Then I diff them.

var difftime = moment(to).diff(from);

If from is '2015-01-01 00:00:00' and 'to' is '2015-01-02 00:00:00', I will get the difftime is '86400000' (Seems like milliseconds format).

My problem.

How can I make difftime(86400000) transfer to YYYY:MM:DD HH:mm:ss(0000:00:01 00:00:00) using 'moment.js' .

diff gives you a duration as milliseconds if you don't specify the unit. And unfortunately, there is no way for format a duration with momentjs.

Your best bet is to use this plugin: https://github.com/jsmreese/moment-duration-format/

Or you can do it manually. Create a moment.duration() object and create the string manually.

var from = moment();
var to   = moment().milliseconds(ms);
var dif = moment.duration(to.diff(from));
var string = dif.years() + "-" + dif.months() + "-" + dif.days() ...

But then you have to worry about padding zeros and it becomes a pain. So just use the plugin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM