admin管理员组

文章数量:1134248

I have two string dates in the format of m/d/yyyy. For example, “11/1/2012”, “1/2/2013”. I am writing a function in JavaScript to compare two string dates. The signature of my function is bool isLater(string1, string2), if the date passed by string1 is later than the date passed by string2, it will return true, otherwise false. So, isLater(“1/2/2013”, “11/1/2012”) should return true. How do I write a JavaScript function for this?

I have two string dates in the format of m/d/yyyy. For example, “11/1/2012”, “1/2/2013”. I am writing a function in JavaScript to compare two string dates. The signature of my function is bool isLater(string1, string2), if the date passed by string1 is later than the date passed by string2, it will return true, otherwise false. So, isLater(“1/2/2013”, “11/1/2012”) should return true. How do I write a JavaScript function for this?

Share Improve this question asked Feb 8, 2013 at 20:52 GLPGLP 3,67520 gold badges65 silver badges96 bronze badges 3
  • create two Date objects from your strings and compare them as numbers. – georg Commented Feb 8, 2013 at 20:53
  • 2 convert the strings to native JS datetime objects (see stackoverflow.com/questions/5619202/…). from there it gets easy. – Marc B Commented Feb 8, 2013 at 20:54
  • 1 how do I create two date objects from strings? – GLP Commented Feb 8, 2013 at 20:54
Add a comment  | 

8 Answers 8

Reset to default 188

const d1 = Date.parse("2012-11-01");
const d2 = Date.parse("2012-11-04");

if (d1 < d2) {
  console.log("Error!");
}

Or, as mentioned in the comments, directly compare the strings:

if ("2012-11-01" < "2012-11-04") {
  console.log("Error!");
}

You can simply compare 2 strings

function isLater(dateString1, dateString2) {
  return dateString1 > dateString2
}

Then

isLater("2012-12-01", "2012-11-01")

returns true while

isLater("2012-12-01", "2013-11-01")

returns false

Parse the dates and compare them as you would numbers:

function isLater(str1, str2)
{
    return new Date(str1) > new Date(str2);
}

If you need to support other date format consider a library such as date.js.

Directly parsing a date string that is not in yyyy-mm-dd format, like in the accepted answer does not work. The answer by vitran does work but has some JQuery mixed in so I reworked it a bit.

// Takes two strings as input, format is dd/mm/yyyy
// returns true if d1 is smaller than or equal to d2

function compareDates(d1, d2){
var parts =d1.split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts = d2.split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 <= d2;
}

P.S. would have commented directly to vitran's post but I don't have the rep to do that.

The best way to compare dates without having to change them into date objects and back, is to keep them as strings, but in a standard format that is comparable, which means they are the exact same length and have same syntax, and in logical order of magnitude. I recommend ISO string method in plain javascript new Date().toISOString() or moment moment().toISOString() to do this. The resulting syntax is something like: "2023-01-22T05:00:00.000Z" Notice the T and Z, etc.

Javascript (and MongoDB) is able to compare strings, via simple binary comparison, which means it is comparing every digit, from left to right, and whichever has higher digit first wins. By logically organizing the data from year to milliseconds, via magnitude, it ensures this method works every time. Just to give you an example, if you were measuring distances, and the units are Miles, Yards, Feet, and Inches, to compare two distances, it is obvious that miles need to be compared first, right? Only then the rest matters; if you check inches first and declare the winner, you'll get wrong answers. So similarly, in dates, years have to be compared first because comparison goes from left to right. You can check below via node console:

// strings can be correctly compared.
"9" > "0" == true; "0" > "9" == false

//they have to be in logical order of left to right in magnitude,
//from year to month to date, otherwise you'll let less material number win
"12/31/2000" > "01/01/2999" == true

//separator has to be consistent, because / vs. - matters
"/" > "-" == true; so "2000/01/01" > "2000-12-31" == true; 

//they have to be the same length, add leading zero as necessary
"2017/10/26" > "2017/10/7" == false;  "2017/10/26"  > "2017/10/07" == true

//they have to have consistent syntax
"T" > " " == true;  
"2023-01-22T05:00:00.000Z" > "2023-01-22 06:00:00" == true

All of these things are addressed when you use the ISO String format to store the date, which is the default way Mongo does it. And to answer the question, you can do something like:

const compareDate = new Date("1/2/2013").toISOString()
const baseDate = new Date("11/1/2012").toISOString()

function isLater(string1, string2) {
    return string1 > string2
}

isLater(compareDate, baseDate)

This worked for me in nextjs/react

import { format, parse, isBefore } from "date-fns";

...

{isBefore(new Date(currentDate), new Date(date)) ? (
 <span>Upcoming Event</span>
) : (
 <span>Past Event</span>
)}

...

isBefore(date, dateToCompare)

https://date-fns.org/docs/isBefore

You can use "Date.parse()" to properly compare the dates, but since in most of the comments people are trying to split the string and then trying to add up the digits and compare with obviously wrong logic -not completely.

Here's the trick. If you are breaking the string then compare the parts in nested format.

Compare year with year, month with month and day with day.

<pre><code>

var parts1 = "26/07/2020".split('/');
var parts2 = "26/07/2020".split('/');

var latest = false;

if (parseInt(parts1[2]) > parseInt(parts2[2])) {
    latest = true;
} else if (parseInt(parts1[2]) == parseInt(parts2[2])) {
    if (parseInt(parts1[1]) > parseInt(parts2[1])) {
        latest = true;
    } else if (parseInt(parts1[1]) == parseInt(parts2[1])) {
        if (parseInt(parts1[0]) >= parseInt(parts2[0])) {
            latest = true;
        } 
    }
}

return latest;

</code></pre>

If your date is not in format standar yyyy-mm-dd (2017-02-06) for example 20/06/2016. You can use this code

var parts ='01/07/2016'.val().split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts ='20/06/2016'.val().split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 > d2

本文标签: how to compare two string dates in javascriptStack Overflow