0

I'm working with javascript and I have dates in this format "2016-04-15 1230" (yyyy-MM-dd HHmm) and I want to calculate the difference between these dates in minutes.

Example :

The difference between "2016-04-15 1230" and "2016-04-15 1210" is 20 minutes

Community
  • 1
  • 1
Jean Dupont
  • 177
  • 1
  • 13
  • 2
    Did you try to write some code? – Dekel Jul 17 '16 at 21:11
  • See this [link](http://www.vijayjoshi.org/2008/10/24/faq-calculate-number-of-days-between-two-dates-in-javascript/). – Arnav Borborah Jul 17 '16 at 21:13
  • Yes I've tried this with d3 : var dateFormat = d3.time.format("%Y-%m-%d %HH%MM"); date1=dateFormat.parse(date1); date2=dateFormat.parse(date2); difference=date1.getMinutes()-date2.getMinutes(); – Jean Dupont Jul 17 '16 at 21:14
  • You could try `getTime()` on both, substracting them, then converting milliseconds to minutes. Also read the [docs](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date) pls – Balázs Édes Jul 17 '16 at 21:16

4 Answers4

2

moment.js is a good library for this sort of thing:

var firstTime = moment("2016-04-15 1230", "YYYY-MM-DD HHmm");
var secondTime = moment("2016-04-15 1210", "YYYY-MM-DD HHmm");

var difference = moment.duration(firstTime - secondTime);

console.log(difference.asMinutes()); // 20
user94559
  • 59,196
  • 6
  • 103
  • 103
  • To parse a single format with time and validation requires about 6 lines of code. There are many good parsers and formatters that are much lighter than moment.js (e.g. [*fecha.js*](https://github.com/taylorhakes/fecha), which is not an endorsement, just an example). – RobG Jul 18 '16 at 06:04
0

First you need to get the Date representation of your date values.

/* Helper function that parses date string (format DD-YY-MM HH:mm) 
   to create a JS Date object*/
function getDateFromDateStr(dateStr) {
  var dateParts=dateStr.split(/\D/);
  return new Date(dateParts[0],dateParts[1],dateParts[2],dateParts[3],dateParts[4]);
}

...
... 
/*Use input string to create date objects*/
var str1= "2016-04-15 1210"; 
var str2= "2016-04-15 1230";

var len = str1.length;
var date1 = getDateFromDateStr(str1.slice(0,len-2) + ":" + str1.slice(len-2));
len = str2.length;
var date2 = getDateFromDateStr(str2.slice(0,len-2) + ":" + str2.slice(len-2));

Then you can simply get the difference in milliseconds by using simple subtraction and convert the result in minutes:

var differenceInMinutes = (date2 - date1)/(60*1000);

NOTE - Please keep in mind is that you should ONLY attempt arithmetic operations on Dates in UTC. Or if you can guarantee that they'll always be in the same time zone and won't have any DST.

Mursaleen Ahmad
  • 313
  • 2
  • 10
  • Can't see the point in parsing a string to generate another string to be randomly parsed by Date. If you go to that trouble, give the values to the Date directly and avoid further parsing altogether. Then it will work in every browser without a library. – RobG Jul 18 '16 at 05:00
  • No, the string parsing is needed here. Date constructor expects input date string to be in ISO-8601. That means HHmm needs to be converted to HH:mm – Mursaleen Ahmad Jul 18 '16 at 05:06
  • You totally missed the point. You parse the string to get a different format, then have the Date constructor parse it again. So if you're parsing it, just give the values directly to Date so it doesn't parse it again. That avoids all the issues (there are many) with using the Date constructor for parsing. – RobG Jul 18 '16 at 05:21
  • Sorry, but I still don't completely follow what you're saying. Could you post the relevant code on how Date constructor should be used here? – Mursaleen Ahmad Jul 18 '16 at 05:31
  • See my answers to [*Javascript function to check two date ranges using Date.UTC works in all browsers but Firefox*](http://stackoverflow.com/questions/38428028/javascript-function-to-check-two-date-ranges-using-date-utc-works-in-all-browser/38428329#38428329) and [*how can I collect form input in date format and display it on page*](http://stackoverflow.com/questions/38403672/how-can-i-collect-form-input-in-date-format-and-display-it-on-page/38429047#38429047). Should do the trick. :-) – RobG Jul 18 '16 at 06:02
  • Updated answer to include your suggestion. – Mursaleen Ahmad Jul 19 '16 at 02:52
0

a = new Date('2016-07-21 12:30'); b = new Date('2016-07-21 12:20');

console.log((a-b)/60000);

prints 10.

Also see How to add 30 minutes to a JavaScript Date object?

Community
  • 1
  • 1
Johan Snowgoose
  • 386
  • 3
  • 6
0

Thanks @RobG for correcting me. Here is another go at it. I tried it with the time example given and changing both the minutes and hours of both times. I'm sure this isn't the fastest way but it is a homebrew.

var first = "2016-04-15 1230"

var second ="2016-04-15 1210"


var timeDiff = function(x, y) {

// Gets first hours and cuts it out
hrs1 = first.slice(11, 13);

// Gets second hours and cuts it out
hrs2 = second.slice(11, 13);

// Gets the minutes from first time and cuts it out
min1 = first.slice(13,15);

// Gets the minutes from second time and cuts it out
min2 = second.slice(13,15);

// Subtracts and puts the difference of minutes in minDiff variable
var minDiff = min1 - min2;

// Subtracts and puts the difference of hours in hrsDiff variable  
var hrsDiff = hrs1 - hrs2;

//  If it is negative, make it positive
if(minDiff <0){
minDiff *= -1;
}

if(hrsDiff < 0) {

  hrsDiff *= -1;

}

return ["Diff in hrs: " + hrsDiff, "Difference in Minutes: " + minDiff];

}

Returns: ["Diff in hrs: 0", "Difference in Minutes: 20"]

With times: "2016-04-15 1530", and "2016-04-15 1248",

Returns: ["Diff in hrs: 3", "Difference in Minutes: 18"]

Hope this was helpful.

DGwang
  • 159
  • 1
  • 14
  • It "works" only because the hour is the same. The value at the end is hours and minutes, not minutes, so `"1230" - "1210"` "works" but `"1330" - "1230"` does not (returns 100, not 60). – RobG Jul 18 '16 at 05:03