I would like to compare two dates directly in the html component, with ngIf
I tried with this code, but it didn't work,
I wanted when today's date was greater than the vPromoData date not to show the contents of my div
<div *ngIf=" item.tabela.vPromo && today < item.tabela.vPromoData " >{{item.tabela.vPromoData | json}}</div>
public today = new Date();
"tabela": {
"itemTabela_id": 2,
"item_id": 7650,
"vVenda": 95.9,
"vPromo": 77.5,
"vPromoData": "2022-09-25"
}
CodePudding user response:
Use the timestamps of each date.
You can get it with yourDate.getTime()
, it returns a number that you can then compare.
const date = new Date();
const now = Date.now();
const yesterday = date.setHours(-24);
console.log(now);
console.log(yesterday);
console.log(now > yesterday);
EDIT
With string date-likes
const date = '2022-10-18';
const now = new Date(...date.split('-')).getTime();
const yesterday = new Date(...date.split('-')).setHours(-24);
console.log(now);
console.log(yesterday);
console.log(now > yesterday);
CodePudding user response:
As you has the date in format yyyy-MM-dd you can compare "string", the only is convert to string "today"
dateToString(date:any)
{
return date.getFullYear() '-'
('00' (date.getMonth() 1)).slice(-2) '-'
('00' date.getDate()).slice(-2)
}
//And use
todayTxt:string=this.dateToString(new Date());
CodePudding user response:
You can easily get yyyy-MM-dd
from Date object from toISOString
and chopping the unnecessary part, sth along the lines
const todayAsString = new Date().toISOString().split('T').shift();
console.log(todayAsString);
But: Angular has a built-in pipe, date
, for formatting dates. Just use it in the template
<div *ngIf="item.tabela.vPromo && (today | date: 'yyyy-MM-dd') < item.tabela.vPromoData">
CodePudding user response:
When working with dates use some well tested and robust library like date-fns that is tree-shakeable, supports locales and works with built-in Date objects too.
isAfter(
parse(item.tabela.vPromoData, 'yyyy-MM-dd', new Date()),
new Date()
)