Check time difference in Javascript
Asked Answered
C

19

140

How would you check time difference from two text-boxes in Javascript?

Centrality answered 24/11, 2009 at 5:12 Comment(6)
What format is the user entering the times?Keratose
That is answered in #42448Kulp
i need only the time conversions, not with date.Centrality
Dates, times: they're all the same thing. Notice in the answers how they mix dates and times without caution!Kulp
Are they two text boxes containing ONLY time values? Such as "11:42pm" or "8:09am"?Sayles
momentjs.com - A javascript date library for parsing, validating, manipulating, and formatting dates.Eyesore
C
190

You can subtract two Date objects to get their difference:

let time1 = "09:00";
let time2 = "17:00";

// given a time value as a string in 24 hour format
// create a Date object using an arbitrary date part,
// specified time and UTC timezone

let date1 = new Date(`2000-01-01T${time1}Z`);
let date2 = new Date(`2000-01-01T${time2}Z`);

// the following is to handle cases where the times are on the opposite side of
// midnight e.g. when you want to get the difference between 9:00 PM and 5:00 AM

if (date2 < date1) {
  date2.setDate(date2.getDate() + 1);
}

let diff = date2 - date1;
console.log(diff);

// the result is 28800000 milliseconds (8 hours)

You can then convert milliseconds to hour, minute and seconds like this:

let diff = 29554456;

let ms = diff % 1000;
let ss = Math.floor(diff / 1000) % 60;
let mm = Math.floor(diff / 1000 / 60) % 60;
let hh = Math.floor(diff / 1000 / 60 / 60);

console.log(`${diff}ms = ${hh}hr, ${mm}min, ${ss}sec, ${ms}ms`);

You can convert time as string to 24-hour format like this:

function parseTime(s) {
  let part = s.match(/(\d{2}):(\d{2})\s*(am|pm)?/i);
  let hh = Number(part[1]);
  let mm = Number(part[2]);
  let ap = part[3] ? part[3].toUpperCase() : null;
  if (ap === "AM") {
    if (hh === 12) {
      hh = 0;
    }
  }
  if (ap === "PM") {
    if (hh !== 12) {
      hh += 12;
    }
  }
  return `${hh.toString().padStart(2, "0")}:${mm.toString().padStart(2, "0")}`;
}
let tests = ["12:00 AM", "12:00 PM", "01:01 PM", "23:59"];
tests.forEach((timeString) => {
  console.log(`${timeString} => ${parseTime(timeString)}`);
});
Clairvoyance answered 24/11, 2009 at 5:52 Comment(6)
I never know if dates in this format will be parsed as d/m/y or m/d/y. The official formats accepted are here (whatever Date.parse() accepts is valid), developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…Polley
what's the +1 about here? What part of the date is that incrementing?Silverts
I know this is ancient, but where in all this gibberish does anything get read from form fields? All I see is some hard-coded example code. How do I get the difference between whatever times my user typed into my two input type="text" boxes, rather than between 9:00 AM and 5:00 PM?Koan
@SalmanA: thanks! That's very helpful. Why did that get removed from the current revision?Koan
How do i get time diffrence between date = "2016/03/01 11:00" to date ="2016/03/06 11:00"Finland
@Koan user interaction (parsing strings in some format or another) and diffing dates are totally separate concerns. It's true that OP asked for input parsing as well as time difference, but no details were given as to what format(s) they're enforcing. Although the question is off-topic (yet has become canonical), this answer solves the most relevant part of the question that's unambiguous enough to do.Exalted
M
28

Here's the solution that worked for me:

var date1 = new Date("08/05/2015 23:41:20");
var date2 = new Date("08/06/2015 02:56:32");

var diff = date2.getTime() - date1.getTime();

var msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;

console.log(hh + ":" + mm + ":" + ss);
Mugger answered 6/8, 2015 at 7:13 Comment(0)
E
24

This function returns a string with the difference from a datetime string and the current datetime.

function get_time_diff( datetime )
{
    var datetime = typeof datetime !== 'undefined' ? datetime : "2014-01-01 01:02:03.123456";

    var datetime = new Date( datetime ).getTime();
    var now = new Date().getTime();

    if( isNaN(datetime) )
    {
        return "";
    }

    console.log( datetime + " " + now);

    if (datetime < now) {
        var milisec_diff = now - datetime;
    }else{
        var milisec_diff = datetime - now;
    }

    var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));

    var date_diff = new Date( milisec_diff );

    return days + " Days "+ date_diff.getHours() + " Hours " + date_diff.getMinutes() + " Minutes " + date_diff.getSeconds() + " Seconds";
}

Tested in the Google Chrome console (press F12)

get_time_diff()
1388534523123 1375877555722
"146 Days 12 Hours 49 Minutes 27 Seconds"
Eyesore answered 7/8, 2013 at 12:18 Comment(3)
How do i get time diffrence between date = "2016/03/01 11:00" to date ="2016/03/06 11:00". and also how do i formate date for above functionFinland
momentjs.com will solve your problems when working with time and dates in javascriptEyesore
momentjs.com/docs/#/displaying/difference Is when you need to calculate the difference between moment objectsEyesore
P
10

Here is my rendition....

function get_time_difference(earlierDate, laterDate) 
{
    var oDiff = new Object();

    //  Calculate Differences
    //  -------------------------------------------------------------------  //
    var nTotalDiff = laterDate.getTime() - earlierDate.getTime();

    oDiff.days = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24);
    nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;

    oDiff.hours = Math.floor(nTotalDiff / 1000 / 60 / 60);
    nTotalDiff -= oDiff.hours * 1000 * 60 * 60;

    oDiff.minutes = Math.floor(nTotalDiff / 1000 / 60);
    nTotalDiff -= oDiff.minutes * 1000 * 60;

    oDiff.seconds = Math.floor(nTotalDiff / 1000);
    //  -------------------------------------------------------------------  //

    //  Format Duration
    //  -------------------------------------------------------------------  //
    //  Format Hours
    var hourtext = '00';
    if (oDiff.days > 0){ hourtext = String(oDiff.days);}
    if (hourtext.length == 1){hourtext = '0' + hourtext};

    //  Format Minutes
    var mintext = '00';
    if (oDiff.minutes > 0){ mintext = String(oDiff.minutes);}
    if (mintext.length == 1) { mintext = '0' + mintext };

    //  Format Seconds
    var sectext = '00';
    if (oDiff.seconds > 0) { sectext = String(oDiff.seconds); }
    if (sectext.length == 1) { sectext = '0' + sectext };

    //  Set Duration
    var sDuration = hourtext + ':' + mintext + ':' + sectext;
    oDiff.duration = sDuration;
    //  -------------------------------------------------------------------  //

    return oDiff;
}
Pilsudski answered 22/10, 2011 at 21:22 Comment(2)
Note: duration is missing the # of daysBrogle
hourtext is using oDiff.days, and hours are not used to compute the durationClot
M
5

A good solution is avaliable at

http://blogs.digitss.com/javascript/calculate-datetime-difference-simple-javascript-code-snippet/

gives the output in your desired differnece format of

days : hours : minutes : seconds .

A slightly modified version of that code is shown below

 var vdaysdiff; // difference of the dates
   var vhourDiff;
   var vmindiff;
   var vsecdiff;

   vdaysdiff = Math.floor(diff/1000/60/60/24);  // in days
   diff -= vdaysdiff*1000*60*60*24;

   vhourDiff = Math.floor(diff/1000/60/60);  // in hours
   diff -= vhourDiff*1000*60*60;

   vmindiff = Math.floor(diff/1000/60); // in minutes
   diff -= vmindiff*1000*60;

   vsecdiff= Math.floor(diff/1000);  // in seconds

   //Text formatting
   var hourtext = '00';
   if (hourDiff > 0){ hourtext = String(hourDiff);}
   if (hourtext.length == 1){hourtext = '0' + hourtext};                                                              

   var mintext = '00';                           
   if (mindiff > 0){ mintext = String(mindiff);}
   if (mintext.length == 1){mintext = '0' + mintext};

  //shows output as HH:MM ( i needed shorter duration)
   duration.value= hourtext + ':' + mintext;
Metopic answered 21/4, 2011 at 13:38 Comment(0)
A
5

The time diff in milliseconds

firstDate.getTime() - secondDate.getTime() 
Along answered 1/3, 2017 at 9:25 Comment(0)
S
4

This is an addition to dmd733's answer. I fixed the bug with Day duration (well I hope I did, haven't been able to test every case).

I also quickly added a String property to the result that holds the general time passed (sorry for the bad nested ifs!!). For example if used for UI and indicating when something was updated (like a RSS feed). Kind of out of place but nice-to-have:

function getTimeDiffAndPrettyText(oDatePublished) {

  var oResult = {};

  var oToday = new Date();

  var nDiff = oToday.getTime() - oDatePublished.getTime();

  // Get diff in days
  oResult.days = Math.floor(nDiff / 1000 / 60 / 60 / 24);
  nDiff -= oResult.days * 1000 * 60 * 60 * 24;

  // Get diff in hours
  oResult.hours = Math.floor(nDiff / 1000 / 60 / 60);
  nDiff -= oResult.hours * 1000 * 60 * 60;

  // Get diff in minutes
  oResult.minutes = Math.floor(nDiff / 1000 / 60);
  nDiff -= oResult.minutes * 1000 * 60;

  // Get diff in seconds
  oResult.seconds = Math.floor(nDiff / 1000);

  // Render the diffs into friendly duration string

  // Days
  var sDays = '00';
  if (oResult.days > 0) {
      sDays = String(oResult.days);
  }
  if (sDays.length === 1) {
      sDays = '0' + sDays;
  }

  // Format Hours
  var sHour = '00';
  if (oResult.hours > 0) {
      sHour = String(oResult.hours);
  }
  if (sHour.length === 1) {
      sHour = '0' + sHour;
  }

  //  Format Minutes
  var sMins = '00';
  if (oResult.minutes > 0) {
      sMins = String(oResult.minutes);
  }
  if (sMins.length === 1) {
      sMins = '0' + sMins;
  }

  //  Format Seconds
  var sSecs = '00';
  if (oResult.seconds > 0) {
      sSecs = String(oResult.seconds);
  }
  if (sSecs.length === 1) {
      sSecs = '0' + sSecs;
  }

  //  Set Duration
  var sDuration = sDays + ':' + sHour + ':' + sMins + ':' + sSecs;
  oResult.duration = sDuration;

  // Set friendly text for printing
  if(oResult.days === 0) {

      if(oResult.hours === 0) {

          if(oResult.minutes === 0) {
              var sSecHolder = oResult.seconds > 1 ? 'Seconds' : 'Second';
              oResult.friendlyNiceText = oResult.seconds + ' ' + sSecHolder + ' ago';
          } else { 
              var sMinutesHolder = oResult.minutes > 1 ? 'Minutes' : 'Minute';
              oResult.friendlyNiceText = oResult.minutes + ' ' + sMinutesHolder + ' ago';
          }

      } else {
          var sHourHolder = oResult.hours > 1 ? 'Hours' : 'Hour';
          oResult.friendlyNiceText = oResult.hours + ' ' + sHourHolder + ' ago';
      }
  } else { 
      var sDayHolder = oResult.days > 1 ? 'Days' : 'Day';
      oResult.friendlyNiceText = oResult.days + ' ' + sDayHolder + ' ago';
  }

  return oResult;
}
Senator answered 24/9, 2014 at 13:6 Comment(0)
G
3

When i tried the difference between same time stamp it gave 0 Days 5 Hours 30 Minutes

so to get it exactly i have subtracted 5 hours and 30 min

function get_time_diff( datetime )
{
var datetime = typeof datetime !== 'undefined' ? datetime : "2014-01-01 01:02:03.123456";

var datetime = new Date(datetime).getTime();
var now = new Date().getTime();

if( isNaN(datetime) )
{
    return "";
}

console.log( datetime + " " + now);

if (datetime < now) {
    var milisec_diff = now - datetime;
}else{
    var milisec_diff = datetime - now;
}

var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));

var date_diff = new Date( milisec_diff );

return days + "d "+ (date_diff.getHours() - 5) + "h " + (date_diff.getMinutes() - 30) + "m";
}
Gentilesse answered 5/2, 2014 at 16:25 Comment(0)
A
3

I have done some enhancements for timer counter

//example return : 01:23:02:02
//               : 1 Day 01:23:02:02
//               : 2 Days 01:23:02:02 


function get_timeDifference(strtdatetime) {
    var datetime = new Date(strtdatetime).getTime();
    var now = new Date().getTime();

    if (isNaN(datetime)) {
        return "";
    }

    //console.log(datetime + " " + now);

    if (datetime < now) {
        var milisec_diff = now - datetime;
    } else {
        var milisec_diff = datetime - now;
    }

    var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));

    var date_diff = new Date(milisec_diff);





    var msec = milisec_diff;
    var hh = Math.floor(msec / 1000 / 60 / 60);
    msec -= hh * 1000 * 60 * 60;
    var mm = Math.floor(msec / 1000 / 60);
    msec -= mm * 1000 * 60;
    var ss = Math.floor(msec / 1000);
    msec -= ss * 1000


    var daylabel = "";
    if (days > 0) {
        var grammar = " ";
        if (days > 1) grammar = "s " 
        var hrreset = days * 24;
        hh = hh - hrreset;
        daylabel = days + " Day" + grammar ;
    }


    //  Format Hours
    var hourtext = '00';
    hourtext = String(hh);
    if (hourtext.length == 1) { hourtext = '0' + hourtext };

    //  Format Minutes
    var mintext = '00';
    mintext = String(mm); 
    if (mintext.length == 1) { mintext = '0' + mintext };

    //  Format Seconds
    var sectext = '00';
    sectext = String(ss); 
    if (sectext.length == 1) { sectext = '0' + sectext };

    var msectext = '00';
    msectext = String(msec);
    msectext = msectext.substring(0, 1);
    if (msectext.length == 1) { msectext = '0' + msectext };

    return daylabel + hourtext + ":" + mintext + ":" + sectext + ":" + msectext;
}
Asphyxia answered 23/7, 2017 at 2:41 Comment(0)
O
3

Try This :

function SumHours() {
  var smon = document.getElementById('sMon').value ;
  var fmon = document.getElementById('fMon').value ;
  var diff = 0 ;
  if (smon && fmon) {
    smon = ConvertToSeconds(smon);
    fmon = ConvertToSeconds(fmon);
    diff = Math.abs( fmon - smon ) ;
    console.log( 'time difference is : ' + secondsTohhmmss(diff) );
  }

  function ConvertToSeconds(time) {
    var splitTime = time.split(":");
    return splitTime[0] * 3600 + splitTime[1] * 60;
  }

  function secondsTohhmmss(secs) {
    var hours = parseInt(secs / 3600);
    var seconds = parseInt(secs % 3600);
    var minutes = parseInt(seconds / 60) ;
    return hours + "hours : " + minutes + "minutes ";
  }
}
<td>
  <input type="time" class="dataInput" id="sMon" onchange="SumHours();" />
</td>

<td>
  <input type="time" class="dataInputt" id="fMon" onchange="SumHours();"/>
</td>
Osteo answered 7/9, 2018 at 4:12 Comment(0)
M
2

I would use just getTime(); and for example Date.now() to return difference in milliseconds:

 //specified date:

var oneDate = new Date("November 02, 2017 06:00:00");

//number of milliseconds since midnight Jan 1 1970 till specified date

var oneDateMiliseconds = oneDate.getTime();

////number of milliseconds since midnight Jan 1 1970 till now

var currentMiliseconds = Date.now(); 

//return time difference in miliseconds

alert(currentMiliseconds-oneDateMiliseconds);
Miraculous answered 2/11, 2017 at 11:54 Comment(0)
A
1

In my case, I'm gonna store the time in milliseconds on chrome storage and try to find diff in hours later.

function timeDiffInHours(milliseconds){
    time_diff = (new Date).getTime() - milliseconds
    return parseInt((time_diff/(1000*60*60)) % 24)
}

// This is again sending current time and diff would be 0.
timeDiffInHours((new Date).getTime());  
Accusation answered 16/5, 2017 at 11:56 Comment(0)
P
1

You can get two time different with this function.

 /**
     * Get Two Time Different
     * @param join
     * @param lastSeen
     * @param now
     * @returns {string}
     */
    function getTimeDiff( join, lastSeen, now = false)
    {
        let t1 = new Date(join).getTime(), t2 = new Date(lastSeen).getTime(), milliseconds =0, time ='';
        if (now) t2 = Date.now();
        if( isNaN(t1) || isNaN(t2) ) return '';
        if (t1 < t2) milliseconds = t2 - t1; else milliseconds = t1 - t2;
        var days = Math.floor(milliseconds / 1000 / 60 / (60 * 24));
        var date_diff = new Date( milliseconds );
        if (days > 0) time += days + 'd ';
        if (date_diff.getHours() > 0) time += date_diff.getHours() + 'h ';
        if (date_diff.getMinutes() > 0) time += date_diff.getMinutes() + 'm ';
        if (date_diff.getSeconds() > 0) time += date_diff.getSeconds() + 's ';
        return time;
    }
    
    
    console.log(getTimeDiff(1578852606608, 1579530945513));
    
Philipines answered 20/1, 2020 at 19:22 Comment(0)
K
0

I like doing it via Epoch.

var now = new Date();
var future = new Date(now.setMinutes(15));

var futureEpoch = moment(future).unix();
var nowEpoch = moment(now).unix();
var differenceInEpoch = nowEpoch - scheduledEpoch ;

console.log("futureEpoch        : " + futureEpoch);
console.log("nowEpoch              : " + nowEpoch);
console.log("differenceInEpoch     : " + differenceInEpoch);

var diffTime = new Date(0); // The 0 there is the key, which sets the date to the epoch
diffTime.setUTCSeconds(differenceInEpoch);
console.log("new diffTime : " + diffTime);
Kuwait answered 3/9, 2016 at 13:43 Comment(0)
R
0

You can use moment js for this purpose. momentJs 'fromNow()' will give you any time difference from current time.

var m1 = any date time on moment format;

console.log(m1.fromNow());
Ratline answered 27/3, 2019 at 11:16 Comment(0)
G
0
var moment = require("moment");
var momentDurationFormatSetup = require("moment-duration-format")

var now  = "2015-07-16T16:33:39.113Z";
var then = "2015-06-16T22:33:39.113Z";

var ms = moment(now,"YYYY-MM-DD'T'HH:mm:ss:SSSZ").diff(moment(then,"YYYY-MM-DD'T'HH:mm:ss:SSSZ"));
var d = moment.duration(ms);
var s = d.format("dd:hh:mm:ss");
console.log(s);
Graybeard answered 10/8, 2020 at 21:27 Comment(0)
M
0

You can set your custom difference by inserting values in end and updatedAt

getDifference(theDate: string): string {
let end = moment(moment(moment()).valueOf());
let updatedAt = moment(new Date(theDate).valueOf());
let diff = end.diff(updatedAt, "hour", false);
if (diff > 8760) {
  diff = end.diff(updatedAt, "years", false);
  return diff > 1 ? diff + " years ago" : diff + " year ago";
} else if (diff > 730) {
  diff = end.diff(updatedAt, "months", false);
  return diff > 1 ? diff + " months ago" : diff + " month ago";
} else if (diff > 24) {
  diff = end.diff(updatedAt, "days", false);
  return diff > 1 ? diff + " days ago" : diff + " day ago";
} else if (diff <= 0) {
  diff = end.diff(updatedAt, "minutes", false);
  return diff > 1 ? diff + " minutes ago" : diff + " minute ago";
} else return diff > 1 ? diff + " hours ago" : diff + " hour ago";

}

Modernize answered 5/10, 2020 at 14:11 Comment(0)
S
0

get outputs like "6 hours, 23 minutes, 27 seconds", or "3 years, 5 months, 3 days, 14 hours, 3 minutes, 3 seconds".

let MILISECONDS = 1000
let YEAR_IN_SECONDS = 31536000
let MONTHS_IN_SECONDS = 2592000
let DAY_IN_SECONDS = 86400
let HOUR_IN_SECONDS = 3600
let MINUTES_IN_SECONDS = 60

let TIME_LENGTHS = [
  {seconds: YEAR_IN_SECONDS, term: 'years'},
  {seconds: MONTHS_IN_SECONDS, term: 'months'},
  {seconds: DAY_IN_SECONDS, term: 'days'},
  {seconds: HOUR_IN_SECONDS, term: 'hours'},
  {seconds: MINUTES_IN_SECONDS, term: 'minutes'},
  {seconds: 1, term: 'seconds'}
]
  const timeInUnitsFormat = function (start) {
  let messageJoins = []
  let now = new Date()
  let diffInSeconds = parseInt((now.getTime() - start.getTime()) / MILISECONDS)
  for (let tl of TIME_LENGTHS) {
    if (diffInSeconds >= tl.seconds) {
      let num_of_times = diffInSeconds / tl.seconds
      diffInSeconds = diffInSeconds % tl.seconds
      messageJoins.push(`${num_of_times} ${tl.term}`)
    }
  }
  return messageJoins.join(',')
}
Success answered 26/5, 2021 at 15:22 Comment(0)
L
0

Started with Ehsan's answer, but that deliberately captures the absolute value. The difference between 4 PM and 1 AM (9 hours) was calculated as 15 hours.

function hoursDiff() {
  let sTime = document.getElementById('sTime').value,
    eTime = document.getElementById('eTime').value;

  if (sTime && eTime) {
    let diff = toSeconds(eTime) - toSeconds(sTime);
    if (diff < 0) diff = 86400 + diff; // adding because diff is negative
    console.log('time difference is : ' + fromSeconds(diff));
  }

  function toSeconds(time) {
    let splitTime = time.split(":");
    return splitTime[0] * 3600 + splitTime[1] * 60;
  }

  function fromSeconds(secs) {
    let hours = parseInt(secs / 3600),
      seconds = parseInt(secs % 3600),
      minutes = parseInt(seconds / 60);
    return hours + "hours : " + minutes + "minutes ";
  }
}
<td>
  <input type="time" class="dataInput" id="sTime" onchange="hoursDiff();" />
</td>

<td>
  <input type="time" class="dataInputt" id="eTime" onchange="hoursDiff();"/>
</td>

And here's how I'm going to use it.

I don't actually need fromSeconds, that's just for illustration here.

I'm going to return diff to schedule the first instance of an interval for cron job after server start. That will look something like this

setTimeout(() => {
    myCronFunc();
    setInterval(myCronFunc, 86400 * 1000);
  },hoursDiff(new Date().toLocaleTimeString("en-us", {timeStyle: "medium"}), "1:00:00 AM"));

function hoursDiff(sTime, eTime) {

  if (sTime && eTime) {
    let diff = toSeconds(eTime) - toSeconds(sTime);
    if (diff < 0) diff = 86400 + diff; // adding because diff is negative
    console.log(diff);
    console.log('time difference is : ' + fromSeconds(diff));
    return diff * 1000;
  }

  function toSeconds(time) {
    let splitTime = time.split(/[: ]/);
    if (splitTime[3].toUpperCase() == 'PM') splitTime[0] = +splitTime[0] + 12;
    return (splitTime[0] * 3600) + (splitTime[1] * 60) + +splitTime[2];
  }

  function fromSeconds(secs) {
    let hours = parseInt(secs / 3600),
      seconds = parseInt(secs % 3600),
      minutes = parseInt(seconds / 60);
    return hours + "hours : " + minutes + "minutes ";
  }
}

hoursDiff(new Date().toLocaleTimeString("en-us", {timeStyle: "medium"}),"9:00:00 AM");
Lemke answered 17/6, 2022 at 15:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.