How to Compare Two Dates

Compare two dates with JavaScript

The Date object will do what you want - construct one for each date, then compare them using the >, <, <= or >=.

The ==, !=, ===, and !== operators require you to use date.getTime() as in

var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();

to be clear just checking for equality directly with the date objects won't work

var d1 = new Date();
var d2 = new Date(d1);

console.log(d1 == d2); // prints false (wrong!)
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true (wrong!)
console.log(d1 !== d2); // prints true (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)

I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.


For the curious, date.getTime() documentation:

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)

How to compare two dates of different format?

If you're getting dates in above format, then you need to convert 2nd data string to make it parseable by Unix date command first. Here is an example:

#!/usr/bin/env bash

dt1='Wed 31 Oct 2018 08:42:00 AM UTC'
dt2='12-10-2018 14:37:42'

dt2=$(sed -E 's/^([0-9]{2}-[0-9]{2})-([0-9]{4})/\2-\1/' <<< "$dt2")
echo "$dt2" # 2018-12-10 14:37:42

# compare EPOCH second values of both dates

if (( $(date -d "$dt1" '+%s') < $(date -d "$dt2" '+%s') )); then
echo "date1 is less than date2"
else
echo "date1 is >= than date2"
fi

How to compare two dates from input?

This is how I would do it

HTML

<script>
function compareDates() {
//Get the text in the elements
var from = document.getElementById('from').textContent;
var to = document.getElementById('to').textContent;

//Generate an array where the first element is the year, second is month and third is day
var splitFrom = from.split('/');
var splitTo = to.split('/');

//Create a date object from the arrays
var fromDate = Date.parse(splitFrom[0], splitFrom[1] - 1, splitFrom[2]);
var toDate = Date.parse(splitTo[0], splitTo[1] - 1, splitTo[2]);

//Return the result of the comparison
return fromDate < toDate;
}
</script>

<input id="from" type="date" placeholder="dd/mm/yy"><br>
<input id="to" type="date" placeholder="dd/mm/yy">
<button onclick="compareDates()">Compare</button>

Let me know how you get on.

Comparing two dates in Go using string types

If you represent both dates with equal number of digits (same width for all year, month and date values), and since the order of fields are from higher priority to lower (year -> month -> day), this will always be correct (string comparison also proceeds from left-to-right).

Note: When the year reaches 10000, this comparison may give wrong results, because the first assumption will not be true (same width for all year values). If you want to handle years beyond 9999, you'll have to represent years with 5 digits, so 2021 must be written as 02021.

Comparing two dates with different years

Don't convert the date to string to compare as you did since it will do the string comparison instead of date comparison. If you did, even it will treat 22/11/2016 is greater than 20/12/2016 within the same year.

You can simply use either today > renewalDate or today.getTime() > renewalDate.getTime() as below,

Method 1:

var renewalDate = new Date(2017, 0, 1);var today = new Date();
if(today > renewalDate){ alert("Date is greater than today");}else{ alert("Date is less than today");}

how to compare two string dates in javascript?

var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
alert ("Error!");
}

Demo Jsfiddle

Recently found out from a comment you can directly compare strings like below

if ("2012-11-01" < "2012-11-04") {
alert ("Error!");
}

How to compare two dates?

Use the datetime method and the operator < and its kin.

>>> from datetime import datetime, timedelta
>>> past = datetime.now() - timedelta(days=1)
>>> present = datetime.now()
>>> past < present
True
>>> datetime(3000, 1, 1) < present
False
>>> present - datetime(2000, 4, 4)
datetime.timedelta(4242, 75703, 762105)

Comparing two dates from a form

First, do this:

function myStringToDate(str) {
var arr = str.split("/"); // split string at slashes to make an array
var yyyy = arr[2] - 0; // subtraction converts a string to a number
var jsmm = arr[1] - 1; // subtract 1 because stupid JavaScript month numbering
var dd = arr[0] - 0; // subtraction converts a string to a number
return new Date(yyyy, jsmm, dd); // this gets you your date
}

Then you will have the tool you need for this to work:

function checkDate() {
var d1 = myStringToDate(document.getElementById("date1").value);
var d2 = myStringToDate(document.getElementById("date2").value);
if (d2.getTime() <= d1.getTime()) {
alert("date 2 is not allowed to be smaller than date 1")
} else {
//Success
}
}

Notice that I changed the comparison operator from >= to <= because it seemed that <= better matched your intent. If I was wrong about this, just change it back.

Comparing date part only without comparing time in JavaScript

I'm still learning JavaScript, and the only way that I've found which works for me to compare two dates without the time is to use the setHours method of the Date object and set the hours, minutes, seconds and milliseconds to zero. Then compare the two dates.

For example,

date1 = new Date()
date2 = new Date(2011,8,20)

date2 will be set with hours, minutes, seconds and milliseconds to zero, but date1 will have them set to the time that date1 was created. To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:

date1.setHours(0,0,0,0)

Now you can compare the two dates as DATES only without worrying about time elements.

How to compare two dates along with time in java

Since Date implements Comparable<Date>, it is as easy as:

date1.compareTo(date2);

As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).

Note that Date has also .after() and .before() methods which will return booleans instead.



Related Topics



Leave a reply



Submit