Reputation: 2004
I am trying to compare two dates for example today's date (20/12/2016
) with a date from next year (01/01/2017
). The code works fine if RenewalDate
is for this year for example 22/12/2016
. It only seems to be if the date is for next year that it doesn't recognize that today is not greater than that date
var RenewalDate = new Date(result.RenewalDate);
var month = RenewalDate.getMonth()+1;
var year = RenewalDate.getFullYear();
if(day<10){
day='0'+day
}
if(month<10){
month='0'+month
}
var RenewalDate = day+'/'+month+'/'+year;
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
if(today > RenewalDate)
{
alert("Date is greater than today");
}
else
{
alert("Date is less than today");
}
Upvotes: 2
Views: 1229
Reputation: 12022
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");
}
Method 2:
var renewalDate = new Date(2017, 0, 1);
var today = new Date();
if(today.getTime() > renewalDate.getTime())
{
alert("Date is greater than today");
}
else
{
alert("Date is less than today");
}
Note: Method 1 and Method 2 will do the same.
Upvotes: 3
Reputation: 1051
Technically you are comparing strings not the dates, compare any two date objects you will get correct results or convert it to timestamps date.getTime()
(it is long number), and then compare you will get correct results.
Upvotes: -1
Reputation: 18557
Here is sample code instead what you are doing,
var to = new Date(2016,12,12);
var from = new Date(2017,12,12);
if(to > from){
alert('to is greater than from');
}else{
alert('to is less than from');
}
I hope this sample code will work your requirement
Upvotes: 1
Reputation: 8340
Why don't you use moment.js?
moment('2016-12-20').isAfter('2016-01-02', 'year'); // false
moment('2016-12-20').isAfter('2015-12-31', 'year'); // true
Upvotes: 1