-2

How do I calculate the difference in minutes given two strings. For example say I have

11:00
11:30 

But of course the second string could be 12:11 so I can't subtract just the minutes.

Mitch VanDuyn
  • 2,838
  • 1
  • 22
  • 29
Jennifer
  • 905
  • 9
  • 20
  • 1
    This question really shows a serious lack of research effort. There are many many resources easily found in a search to help get you started. If you have made attempts and are having problems then post that code if you want help – charlietfl Jan 04 '16 at 05:06
  • Possible duplicate of [JavaScript - Get minutes between two dates](http://stackoverflow.com/questions/7709803/javascript-get-minutes-between-two-dates) – rkyr Jan 04 '16 at 05:14
  • I am kind of new on SO, but I think its unfair the judge the questioners experience level. I did a search of "getting difference between time in javascript" and while it does give you the answer, you have to a bit of experience to understand. – Mitch VanDuyn Jan 04 '16 at 05:17
  • Are the times AM or PM? Also, do we assume they are both on the same day? – jkdev Jan 06 '16 at 02:47

2 Answers2

0

first use javascript to convert the strings to time, then subtract, then convert back to strings

like this:

x = new Date("1/1/01 11:00")
y = new Date("1/1/01 11:30")
// now y-x has difference in milliseconds
// (y-x)/1000 is difference in seconds, etc

The data 1/1/01 is just being used as a dummy value, but the one thing you might have to worry about is are the times on different days, if so you will have to use 1/2/01 for the second time. Unless of course you always know the times are in the same day, but if they can cross "midnight" then you have to adjust for that.

You may want to use http://momentjs.com/ which will take care of the details for you.

Mitch VanDuyn
  • 2,838
  • 1
  • 22
  • 29
  • exactly I know the flow but I'm comparing in seconds – Jennifer Jan 04 '16 at 05:02
  • can I skip the date? – Jennifer Jan 04 '16 at 05:09
  • I don't have to worry about the day, i will have a list of time only. But x-y it return int? – Jennifer Jan 04 '16 at 05:13
  • Try it... you can just open up your js console and type all this in and see what it does... But yes when you subtract two dates, you get back the difference in milliseconds. Again though let me emphasize the power of just experimenting in the javascript console in your browser. – Mitch VanDuyn Jan 04 '16 at 05:14
0

When looking for getting metrics such as date , hour , minutes, seconds from the date difference, it's a lot easier to use basic notations as listed here

var x = new Date(new Date().getTime() + 11.5*60*60000); // adds 11 hours - 30 minutes 
var y = new Date(new Date().getTime() + 11*60*60000); // adds 11 hours 
alert(x.getMinutes() - y.getMinutes()); // gives the difference = 30

Here's an example : https://jsfiddle.net/DinoMyte/157knmgn/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26