1

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;
3
  • can you show some code, share a fiddle? Commented Feb 18, 2016 at 10:15
  • here is the code u asked for Commented Feb 18, 2016 at 10:20
  • You could at least show the format of the times. Commented Feb 18, 2016 at 10:42

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

15 Comments

i wanted the different between two times
But this is exactly what his code does, could be more specific or give an example?
@Timon.Z THERE are 2 times 9:00 am and 1:00 pm
1st being th start and second the end time.
@IvanLeonenko—ISO 8601 compliant strings aren't correctly parsed by all browsers in use either, so there are no strings that should be passed to the Date constructor (or Date.parse). And the OP says "times in 12hr format", not dates.
|
0

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!

7 Comments

Thanks. But i know nothing about the moment.js library
This is the right solution, working with times and dates in Javascript can be cumbersome if you don't use any library.
Simply saying "Use library X" is not an answer.
@RobG - giving someone the tools and the direction to go in is much better than spoon feeding an answer. You learn more and grow more... I didnt simply say use lib x - i gave a damn good reason and a damn good lib for use case. Do you know the difference between safari and chrome and how they handle dates? I didnt until i spent 3 hrs debugging it... moment.js would have saved me this time.
@avinoor - moment.js is like lodash for dates... Now u do!
|
0

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

1 Comment

this is pretty close to what i wanted
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.