简体   繁体   中英

How to add 24 hr format into total hours in javascript

How can I add 24:00 time format into total time in javascript?

var time1 = 12:10;
var time2 = 23:40;

Result

var totalTime = 35:50

I tried momentjs using duration but i can't format it :(

从一开始就使用添加方法

moment().add(24, 'hours')

Use moment, it is very easy https://momentjs.com/docs/#/manipulating/add/

//With add
var moment = require('moment');
var time1 = '12:10' //String
var mtime1 = new moment(time1, 'HH:mm'); //Moment object

moment(mtime1).add(2, 'hours').format('HH:mm'); // 14:10
moment(mtime1).add(2, 'hours').hours(); // 14

//Same result with duration
var duration = moment.duration({'hours' : 2});

moment(mtime1).add(duration).format('HH:mm'); // 14:10
moment(mtime1).add(duration).hours(); // 14

If you want to use vanilla javascript instead of a Library, you can refer to the following post: How to add 30 minutes to a JavaScript Date object?

VANILLA JAVASCRIPT

You can use the following code:

function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes*60000);
}

And then you can use add the 24 hours as you wanted:

addMinutes(new Date('2014-11-02'), 60*24);

Please note that you will have a Date object, so you should format by yourself if you want it to be printed nicely.

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