javascriptmomentjsdatejs

Adding two durations together with Datejs or Momentjs, and formating them like "HH:mm:ss"


I would like to add 2 durations together for example: 00:04:00 + 07:23:00 = 07:27:00

    var std_count = "00:06:00";
    var std_create = "07:23:00";

    var time_2 = moment.duration(std_count, "HH:mm:ss");
    var time_3 = moment.duration(std_create, "HH:mm:ss");
    var final = time_2.add(time_3, "HH:mm:ss");

ps. I was unnable to find this kind of addition in moment js or date js. Thanks in advance.


Solution

  • Using DateJS with time.js included, you can take advantage of the TimeSpan class.

    Example

    var std_count = Date.parse("00:06:00").getTimeOfDay();
    var std_create = Date.parse("07:23:00").getTimeOfDay();
    
    var final = std_count.add(std_create);
    
    final.toString("HH:mm:ss");
    // "07:29:00"
    

    or you could pull this off in one chained sequence:

    Date.parse("00:06:00")
        .getTimeOfDay()
        .add(Date.parse("07:23:00").getTimeOfDay())
        .toString("HH:mm:ss");
    

    Hope this helps.