Reputation: 3895
I am new to angular 6 ,Here I need to compare to date inputs and find the greatest one.
input 1 : 2018-12-29T00:00:00
input 2 : Mon Dec 31 2018 00:00:00 GMT+0530 (India Standard Time)
Here I received the input 1 from mssql database and the input 2 from the material datepicker .
while compare this two dates as below I got false.
console.log(mMagazineObject.From < mMagazineObject.To ? true : false);
is there any possibility to compare these two date formats .If yes please help me to fix this .
Upvotes: 24
Views: 105319
Reputation: 2060
I have tried all way to compare 2 dates but below is the best built-in angular method for compare 2 dates.
if (formatDate(FromDate,'yyyy-MM-dd','en_US') > formatDate(ToDate,'yyyy-MM-dd','en_US'))
{
console.log('---Fromdate is greater----');
}
else
{
console.log('---Todate is greater----');
}
Here, first argument of formatDate is date input, second argument is format of date, third argument is locale.
Upvotes: 0
Reputation: 9054
Angular has builtin formatDate method so you can use it to format your date and also compare it simply like below code:
In your component.ts file:
date1 = formatDate(new Date(),'yyyy-MM-dd','en_US');
date2 = let FToday = formatDate(datecomingfromdb,'yyyy-MM-dd','en_US');
if(date1>date2){
console.log('---date1 is greater----');
}else{
console.log('---date2 is greater-----');
}
hope this helps and you can read more in Angular docs here
Upvotes: 10
Reputation: 1900
Using Date.parse(input)
is the best idea for if the APIs change. This provides timestamps, numbers which you can compare easily with the math comparisons.
Upvotes: 1
Reputation: 3895
finally I found the solution.
console.log(mMagazineObject.From < this.datePipe.transform(mMagazineObject.To, 'yyyy-MM-dd') ? true : false);
Upvotes: 2
Reputation: 30565
you can use getTime
if (input1Date.getTime() < input2Date.getTime())
Note that if your dates are in string format, you first need to parse them to Date
Upvotes: 29