avinoor
avinoor

Reputation: 33

Time difference using javascript

What would be the code for finding the time difference between two different times which are in a 12hr format using javascript. I am using these two time fields in my dynamic gridview .

 var gridNew = document.getElementById("<%= Gridview1.ClientID %>");
            if (gridNew.rows.length > 0) {
                for (i = 0; i < gridNew.rows.length - 2; i++) {
                    var frombox = document.getElementById("Gridview1_txtFrom_" + (i));
                    var tobox = document.getElementById("Gridview1_txtTo_" + (i));
                      if(frombox.value<=tobox.value){
                        alert("Enter valid time set");
                        return false;

Upvotes: 1

Views: 206

Answers (4)

Gayan Sandamal
Gayan Sandamal

Reputation: 337

Try this simple plugin to get time differences.

https://github.com/gayanSandamal/good-time

import the goodTimeDiff method from good-time.js to your project

import {goodTimeDiff} from './scripts/good-time.js'

declare an object to give settings like below. let settings = {}

now assign time values to the declared object variable. *time must be in standard format and must be a string! *'from' is optional the default value will be the browser current time.

let settings = {
    'from': '2019-01-13T00:00:29.251Z',
    'to': '2018-09-22T17:15:29.251Z'
}

now calllback the method called goodTimeDiff() and pass the settings object variable as a parameter.

goodTimeDiff(settings)

Finally assign the method to any variable you want.

let lastCommentedTime = goodTimeDiff(timeSettings)

Upvotes: 0

Ivan Leonenko
Ivan Leonenko

Reputation: 2383

Here' how you can get milliseconds time difference between two custom dates.

Math.abs(new Date(firstDateString).getTime() - new Date(secondDateString).getTime());

If you have problems parsing/converting to Date, consider using a library like date.js or moment.js

With moment you could do something like this:

var diff = moment('3:30','HH:mm').diff(moment('3:20','HH:mm'));

If you need am / pm:

var diff = moment('3:30 pm','HH:mm a').diff(moment('3:20 am','HH:mm a'));

Here's jsfiddle

Upvotes: 3

RobG
RobG

Reputation: 147403

You haven't shown the format of the times other than to say they're in "12hr format". An algorithm is to parse and convert them to a common unit, say seconds, find the difference, then format it back into whatever units suit.

So if the times are in h:m:s a/p format like "9:42:15 am" and you want the result in a similar format, then the following functions may help.

/*  Convert time in h:m:s a/p format to seconds
**  Seconds component is optional, h:m is OK
**  Tolerates space before am/pm, leading and trailing whitespace
**  Doesn't validate string
**
**  @param {string} s - time to parse
**  @returns {number} time converted to seconds.
*/
function hmsToSeconds(s) {
  var b = s.match(/\d+/g);
  var am = /am\s*$/i.test(s);
  return ((b[0] % 12) + (am? 0:12))*3600 + (b[1]*60) + (+b[2]||0);
}

/*  Convert seconds to time in h:mm:ss format
**  Maintains sign of input (+/-).
**
**  @param {number} s - seconds to convert
**  @returns {string} seconds converted to h:mm:ss.
*/
function secToHMS(s) {
  function z(n){return (n<10? '0' : '') + n}
  var sign = s < 0? '-' : '';
  s = Math.abs(s);
  return sign + (s/3600 | 0) + ':' + z((s%3600 / 60 |0)) + ':' + z(s%60);
}

function getTimeDifference(t0, t1) {
  return secToHMS(hmsToSeconds(t1) - hmsToSeconds(t0)); 
}

document.write(getTimeDifference('11:32 am','12:38:51pm'));

Upvotes: 0

Sten Muchow
Sten Muchow

Reputation: 6701

Times in JS can be a pain to deal with cross browser, and anyone who has had to debug wierd cross browser behavior can attest to. I have learned than when ever i wanna do anything with dates in JS involve the moment.js lib.

I was reluctant at first as I thought i can just do most everything myself and roll my own. This is a cuban cigar and no amount of home rolling can cover all the tools moment comes with.

I wont tell you how to fix, just give you the tool...

moment().diff

Enjoy!

Upvotes: 0

Related Questions