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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With