'compare two dates in Angular 6
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 .
Solution 1:[1]
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
Solution 2:[2]
finally I found the solution.
console.log(mMagazineObject.From < this.datePipe.transform(mMagazineObject.To, 'yyyy-MM-dd') ? true : false);
Solution 3:[3]
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.
Solution 4:[4]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MJ X |
| Solution 2 | Zhu |
| Solution 3 | Sam96 |
| Solution 4 |
