Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - difference between two time strings [duplicate]

I need to compare two different datetime strings (formed: YYYY-MM-DD'T'HH:mm).

Here are the datetime strings:

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

I've sliced the dates out of them so I only need the 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 I could get the difference between these two times?

Result should look like this:

1 hour 30 minutes

Also if the dates are different is there any easy solution to get the date difference too?

like image 914
IlariM Avatar asked May 02 '17 08:05

IlariM


People also ask

How do you compare two time strings?

To compare two time strings:Get the hour, minute and seconds value from each string. Use the values to create a Date object. Compare the output from calling the getTime() method on the Date objects.

Can we compare time in JavaScript?

In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.

How do you find the difference between two dates in hours?

To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.


1 Answers

Use javascript Date:

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

var minutes = milliseconds / (60000);
like image 179
2oppin Avatar answered Sep 27 '22 23:09

2oppin