JavaScript - difference between two lines of time

I need to compare two different lines of time (formed: YYYY-MM-DD'T'XN: mm ).

Here are the datetime lines:

var a = ("2017-05-02T10:45");
var b = ("2017-05-02T12:15");

I cut dates from them, so I only need time (formed: HH: mm ).

var now = a.slice(11, 16);
var then = b.slice(11, 16);

// now = 10:45
// then = 12:15

Is there any way to get the difference between these two times?

The result should look like this:

1 hour 30 minutes

Also, if the dates are different, is there any simple solution to get the difference in dates?

+4
source share
3 answers

This should help you:

d1 = new Date(Date.parse("2017-05-02T10:45"));
d2 = new Date(Date.parse("2017-05-02T12:15"));

var getDuration = function(d1, d2) {
    d3 = new Date(d2 - d1);
    d0 = new Date(0);

    return {
        getHours: function(){
            return d3.getHours() - d0.getHours();
        },
        getMinutes: function(){
            return d3.getMinutes() - d0.getMinutes();
        },
        getMilliseconds: function() {
            return d3.getMilliseconds() - d0.getMilliseconds();
        },
        toString: function(){
            return this.getHours() + ":" +
                   this.getMinutes() + ":" + 
                   this.getMilliseconds();
        },
    };
}

diff = getDuration(d1, d2);

console.log(diff.toString());
Run codeHide result

momentjs, 1. . 2. - , , (, , ).

0

javascript:

var a = ("2017-05-02T10:45");
var b = ("2017-05-02T12:15");
var milliseconds = ((new Date(a)) - (new Date(b)));

var minutes = milliseconds / (60000);
+3

lib, :

wiki: https://github.com/jiangbai333/Common-tools/wiki/format : https://github.com/jiangbai333/Common-tools/blob/dev/string/string.js

string.js , :

var temp = "short-stamp".format(+new Date("2017-05-02T12:15")) - "short-stamp".format(+new Date("2017-05-02T10:45"));

console.log(parseInt(temp / 3600), "hour", parseInt(temp % 3600 / 60), "minutes")
+1

Source: https://habr.com/ru/post/1676126/


All Articles