100

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?

GLP
  • 3,441
  • 20
  • 59
  • 91
  • create two Date objects from your strings and compare them as numbers. – georg Feb 08 '13 at 20:53
  • 2
    convert the strings to native JS datetime objects (see http://stackoverflow.com/questions/5619202/converting-string-to-date-in-js). from there it gets easy. – Marc B Feb 08 '13 at 20:54
  • 1
    how do I create two date objects from strings? – GLP Feb 08 '13 at 20:54

7 Answers7

180

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!");
}
double-beep
  • 5,031
  • 17
  • 33
  • 41
Garry
  • 4,996
  • 5
  • 32
  • 44
  • 1
    will it work if the format of the dates are 12/31/1992? where MM/dd/YYYY ? – KyelJmD Aug 07 '13 at 08:20
  • 1
    It works for MM/dd/YYYY format as well. @AnttiHaapala It does seem to work with all operator. – Rajush Dec 16 '15 at 19:10
  • 3
    I retracted my comment whereby I claimed that this does not work for `==`, since when I glimpsed at the code I thought it was comparing Date objects. However, `Date.parse` returns an integer instead (now how convenient is that) and this code would work for equality as well. Still, beware that `new Date('2015-10-10') == new Date('2015-10-10')` is false! – Antti Haapala -- Слава Україні Dec 17 '15 at 05:20
  • 2
    It's not working for format DD/MM/yyyy why can anybody pls tell me ?? – Sudhanshu Gaur Jun 25 '16 at 12:28
  • 1
    If you can Post your Code then we will be able to help you out.make sure you are not using New Keyword for Date.parse. Date.parse is only a method. – Garry Nov 15 '16 at 14:36
  • 1
    this assumes that the data format is MM-dd-yyyy, not working wiith dd MM yyyy – behzad Apr 13 '17 at 08:35
  • @behazad. This does not assumes that the data format is MM-dd-yyyy. Date.parse return Integer. Check jsfiddle where i am using yyyy-mm-dd. – Garry Apr 12 '18 at 14:40
  • 4
    Given the date formats, there is no need for *Date.parse*, they can be compared as strings, i.e. `"2012-11-01" < "2012-11-04"`. – RobG Feb 01 '22 at 13:01
20

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

fuyi
  • 2,573
  • 4
  • 23
  • 46
  • 3
    `"2017/10/26" > "2017/10/7"` gives `false` :D – ahmadalibaloch Oct 07 '17 at 12:52
  • 10
    @CaseyC it's not about syntax. It's about the lack of the leading zero before '7'. If you pass exactly `2017/10/26` and `2017/10/7` you'll get `false`. It is important that the format should be very specific for this solution to work. – Max Nov 27 '18 at 16:54
  • @max is right. Not syntax, it's format specific. I deleted my comment because it's misleading. – CaseyC Nov 29 '18 at 00:39
  • what is going on here?? parseInt('2012-12-01') is just 2012. I don't understand what is happening behind the scenes or why this could be okay – Ray Foss Jun 06 '19 at 14:53
  • @RayFoss parseInt tries to match the first integer value it finds. Since 2012 is the first integer in your string, it evaluates to 2012. If you want to get an integer composed of all the digits in your string, you have to manipulate the string to strip out all of your non digit characters. – Steve Pak Sep 16 '19 at 15:42
  • 8
    Despite some confusion in the comments here, this does work for all YYYY-MM-DD dates. The original question was asking about "m/d/yyyy" dates, but most of us are using YYYY-MM-DD internally, so this is the best solution for most cases. – orrd Sep 17 '19 at 17:54
  • 2
    what happens if two dates are equal: "2012-12-01", "2012-12-01" ? – Brooklyn99 Jan 27 '22 at 14:57
15

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.

Matt Zeunert
  • 16,075
  • 6
  • 52
  • 78
3

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.

Steven Kuipers
  • 809
  • 7
  • 19
  • Thank you. This works even for a custom date format. – khwilo Aug 03 '19 at 20:25
  • this works good,we just need to pad zero before single digit months and single digit dates – Jose Kj Nov 01 '19 at 11:50
  • 1
    This wouldn't work... At all. According to this, 1-1-2019 is smaller than 31-12-1985, which is obviously wrong. – almulo Feb 18 '20 at 15:37
  • That is because you don't format the date properly I believe. It should be dd/mm/yyyy – Steven Kuipers Feb 18 '20 at 16:11
  • 1
    It is dd/mm/yyyy. You can check it yourself: 01/01/2019 (1st of January 2019) and 31/12/1985 (31st of december 1985). If you concatenate the parts of each date and then convert them into a number, you get 1,012,019 and 31,121,985. And the second number is obviously bigger than the first one... But the truth is the first date is 30 years bigger than the second one. Even if the sum of its parts was taken as numbers too, it wouldn't work (2021 < 2028) – almulo Mar 03 '20 at 10:40
  • Right. But the function does not sum each date, it splits the string and creates a number that is build up like this yyyymmdd and then compares the two inputs. 20190101 > 19851231. But you do need to pad the day and month. – Steven Kuipers Mar 03 '20 at 11:47
  • This function requires a very specific date format be passed in. This could easily cause bugs in a production codebase due to other developers not understanding that it requires a specific format, just assuming it works with normal date strings. If you have a custom format for dates (which in itself is a bad smell), you would be better off making a function like "standardizeCustomDateFormat" to output a standard date format that can then be compared using Date objects. – Jeremy C Mar 25 '21 at 21:31
0

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

atazmin
  • 4,757
  • 1
  • 32
  • 23
-1

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>
Ankit Mahala
  • 1
  • 1
  • 3
-2

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
vitran
  • 5
  • 1
  • 1
    This doesn't work. It treats all parts of the date with equal significance. You want something like var d1 = Number(parts[2] * 10000 + parts[1] * 100 + parts[0]); – Bumptious Q Bangwhistle Aug 22 '19 at 09:11