Null Pointer
Null Pointer

Reputation: 9289

Compare two time (hh:mm:ss) strings

I have two time strings in hh:mm:ss format. (eg: 12:40:13 and 20:01:01.) How can I compare these in JavaScript?

Upvotes: 2

Views: 24010

Answers (8)

mplungjan
mplungjan

Reputation: 177786

Assuming you have 24 hour times and same padding you can do simple string compare

 var t1 = "12:40:13", t2= "20:01:01";
 if (t1<t2) {
    console.log(t1," is < ", t2);
 }

I prefer to have date objects, but as pointed out elsewhere, you can just convert to seconds if you want to do simple compares

Here is a complete solution with test cases

/* Utility function to create Date objects from time strings */
const createTime = (timeStr) => ((dt) => (dt.setHours(...timeStr.split(":").map(Number), 0), dt))(new Date());

/* Function to compare two time strings and calculate the difference in seconds */
const compareTimes = (time1, time2) => {
  let t1Date = createTime(time1);
  let t2Date = createTime(time2);

  // Calculate difference in seconds
  const dateDiff = (t1, t2) => Math.floor(Math.abs(t1.getTime() - t2.getTime()) / 1000);

  // Compare two times
  const dateCompare = (t1, t2) => {
    if (t1.getTime() > t2.getTime()) return 1;
    if (t1.getTime() < t2.getTime()) return -1;
    return 0;
  };

  return {
    differenceInSeconds: dateDiff(t1Date, t2Date),
    comparisonResult: dateCompare(t1Date, t2Date)
  };
};

// Test set
const testCases = [
  { time1: "12:40:13", time2: "20:01:01" },
  { time1: "00:00:00", time2: "00:00:00" },
  { time1: "23:59:59", time2: "00:00:00" },
  { time1: "23:59:59", time2: "23:59:59" },
  { time1: "00:00:00", time2: "23:59:59" }
];

// Display results for each test case
const output = document.getElementById('output');
const comparisonTexts = { '-1': 'less than', '0': 'equal to', '1': 'greater than' };
testCases.forEach(({ time1, time2 }) => {
  const { differenceInSeconds, comparisonResult } = compareTimes(time1, time2);
  output.innerHTML += `Difference between ${time1} and ${time2} = ${differenceInSeconds} seconds<br/> 
    ${time1} is ${comparisonTexts[comparisonResult] || 'undefined comparison'} ${time2}<hr/>`;
});
<output id="output"></output>

Upvotes: 13

CodeBiker
CodeBiker

Reputation: 3253

Assuming the times are in the same time zone, simply compare the strings.

This evaluates to true:

"12:40:13" < "20:01:01"

Note that the items being compared must use the same hh:mm:ss format (for example, "05:00:00" < "4:00:00" evaluates to true, which is not what you want).

Upvotes: 0

Gusjafo
Gusjafo

Reputation: 21

if you have 2 time string in 24 hour format:

const string1 = new Date().toLocaleTimeString({ hour12: false }); 
const string2 = new Date().toLocaleTimeString({ hour12: false });

you can simply compare these two strings:

string1 < string2 ? 'string1 < string2' : 'string1 > string2';

Upvotes: 0

Hitesh Sadhrakiya
Hitesh Sadhrakiya

Reputation: 19

var time1 = "09:30";
var time2 = "15:30";

var time1InMinutesForTime1 = getTimeAsNumberOfMinutes(time1);
var time1InMinutesForTime2 = getTimeAsNumberOfMinutes(time2);

var time1IsBeforeTime2 = time1InMinutesForTime1 < time1InMinutesForTime2;

function getTimeAsNumberOfMinutes(time) {
    var timeParts = time.split(":");

    var timeInMinutes = (timeParts[0] * 60) + timeParts[1];

    return Number(timeInMinutes);
}

Upvotes: 0

saidesh kilaru
saidesh kilaru

Reputation: 748

 Date.parse('01/01/2011 10:20:45') > Date.parse('01/01/2011 5:10:10')

 The 1st January is an arbitrary date, doesn't mean anything.

Upvotes: 1

twip
twip

Reputation: 648

Here's another take:

function compareTimes(timeOne, timeTwo) {           
    if(daterize(timeOne) > daterize(timeTwo)) return 1;
    if(daterize(timeOne) < daterize(timeTwo)) return -1;
    return 0;
}

function daterize(time) {
    return Date.parse("Thu, 01 Jan 1970 " + time + " GMT");
}

You may also want to take a look at the MDN Javascript docs for Dates. Javascript comes with a lot of gotchas, like Date.month going from 0-11.

Upvotes: 1

RobG
RobG

Reputation: 147363

If "compare" means "see if they are equal", and the two have the same format, why not simply:

var time1 = "12:40:13";
var time2 = "20:01:01";

if (time1 == time2) {
    // do stuff
}

If you need to get the difference in time, the conversion to a date object is one way (see mplungjan's answer) or you can convert them to a common unit (say seconds) and subtract:

function toSeconds(t) {
    var bits = t.split(':');
    return bits[0]*3600 + bits[1]*60 + bits[2]*1;
}

var secs1 = toSeconds(time1);
var secs2 = toSeconds(time2);

// do stuff  - compare, subtract, less than, greater than, whatever

Upvotes: 6

Benny Tjia
Benny Tjia

Reputation: 4883

Here is one suggestion that I modified from the solution in this website here, hope it helps.

function compareTime(time_1, time_2) {
   var s1 = 
       time1.split(":")[0] * 3600 + time1.split(":")[1] * 60 + time1.split(":")[2];
   var s2 = 
       time2.split(":")[0] * 3600 + time2.split(":")[1] * 60 + time1.split(":")[2];
   return Math.abs(s1 - s2); // Gets difference in seconds
}

var time_1 = "12:40:13", time_2 = "20:01:01";
document.write(compareTime(time_1, time_2));

Upvotes: 1

Related Questions