-1

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.

gjman2
  • 912
  • 17
  • 28

1 Answers1

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);
}

http://jsfiddle.net/aYwux/2/

Explanation:

  1. By var parts = time.split(/ |:/); we're splitting 02:30 pm into 3 parts: 02, 30, pm.

  2. 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