How to calculate differences between two time eg(server time=04:30 pm and <p id="orderTime">02:30 pm</p>
) and return it in minutes such as 90 minutes using jquery and javascript. The server time and order time is in 12 hour format not in 24h.
Asked
Active
Viewed 1,896 times
-1

gjman2
- 912
- 17
- 28
-
Will it always be in a `HH:mm am` format? – zerkms Jun 25 '13 at 02:26
-
How is the server time returned? A string? A JSON formatted datetime? Is it stored in a variable? Can you show the code that retrieves it? – pete Jun 25 '13 at 02:27
-
the time is in HH:mm am/pm format and it should return in minutes 00:60 / 60 minutes – gjman2 Jun 25 '13 at 02:27
-
Matt Johnson, I want the time in 12 hours format not in 24 hours – gjman2 Jun 25 '13 at 02:29
-
The server time I simply use the var CurrentDate=new Date(); – gjman2 Jun 25 '13 at 02:30
1 Answers
1
If you can guarantee they always will be of that format, then here is a straightforward solution:
function humanReadableToMinutes(time)
{
var parts = time.split(/ |:/);
return (parts[2] == 'pm' * 12 * 60)
+ parseInt(parts[0], 10) * 60
+ parseInt(parts[1], 10);
}
Explanation:
By
var parts = time.split(/ |:/);
we're splitting02:30 pm
into 3 parts:02
,30
,pm
.return (parts[2] == 'pm' * 12 * 60) + parseInt(parts[0], 10) * 60 + parseInt(parts[1], 10);
contains of 3 operands:* (parts[2] == 'pm' * 12 * 60) --- adds additional 12 hours if it's "pm" * parseInt(parts[0], 10) * 60 - takes hours fraction extracted and converts it to minutes * parseInt(parts[1], 10) - minutes fraction
PS: this solution doesn't take care of 12am
and 12pm
accurately, so it's a homework for the OP

Lee Taylor
- 7,761
- 16
- 33
- 49

zerkms
- 249,484
- 69
- 436
- 539
-
Can you please explain me about your codes. Because I like to try to understand it – gjman2 Jun 25 '13 at 02:35
-
1
-
1
-