Reputation: 461
Seems crazy but I cannot find a way to compare in an html created by jhipster test if a date field is greater than current date.
I try to display the date read from DB and see 2020-12-12 then I try to display the current date. Searching in the net I find it's possibile to get the current date doing: new Date()
. So I try to display this but runnig the page an error is displayed:
ERROR Error: Uncaught (in promise): Error: Template parse errors:
Parser Error: Unexpected token 'Date' at column 5 in [ {{new Date()}} ] in...
how can I get the current date (for checking with the one read from db)?
Here the code of the myclass.component.html where I need to check the date:
<div>
<jhi-alert-error></jhi-alert-error>
...
<div class="table-responsive" *ngIf="myclasses?.length > 0">
<table class="table table-striped" aria-describedby="page-heading">
<thead>
<tr jhiSort [(predicate)]="predicate" [(ascending)]="reverse" [callback]="transition.bind(this)">
<th...
</tr>
</thead>
<tbody>
<tr *ngFor="let myclasse of myclasses ;trackBy: trackId">
<td>{{myclass?.id}}</td>
...
<td>
{{ new Date() }}
</td>
...
Upvotes: 2
Views: 246
Reputation: 3702
Usually, it's much easier to work with dates using the MomentJS library since it is already integrated into JHipster.
If you want to know if a date is in the future, you can define a function in your [entity].component.ts
that returns a boolean, like this:
import * as moment from 'moment';
import { Moment } from 'moment';
...
isFutureDate(date: Moment): boolean {
return moment().isBefore(date);
}
Then in your [entity].component.html
you can call it like this:
<td>
Date is in the future: {{ isFutureDate(myclass.date) }}
</td>
Where myclass.date
is the date you want to check.
If what you need is just to know the difference between that date and now, you can do that too very easily. In your ...component.ts
:
import * as moment from 'moment';
import { Moment } from 'moment';
...
getDateDiff(date: Moment): number {
const diff = date.diff(moment());
const duration = moment.duration(diff);
return duration.asHours();
}
And in your ...component.html
:
<td>
Difference in hours: {{ getDateDiff(myclass.date) | number: '2.0-0' }} hours
</td>
In this case getDateDiff()
will return the difference in hours between the date you pass as argument (myclass.date
) and the current date (moment()
). It will be a negative number if the date to check is in the past.
MomentJS is a very powerful library you can check the full documentation here. Also, if you want, the documentation relative to the methods I used:
Upvotes: 3