Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate total days between now and a declared day in Angular?

Hello I would like to compare a day with the current date and get the total days.

If the total day is greater than 50 than set "fiffty".

I think the last part is easy but i cant get the solution for get the total days and compare them.

is there a function like this?

<td><div *ngIf="todo.anyDate>-dateNow()>50">fiffty</div> </td>

Thanks for helping

like image 602
BVB1392 Avatar asked Dec 05 '25 18:12

BVB1392


2 Answers

Without using momentjs, you would have to define a function in your component:

public inBetween(date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;

  // Convert back to days and return
  return Math.round(difference_ms/one_day); 
}

Source

Then, in your *ngIf you would do inBetween(anyDate, new Date())

like image 50
Boland Avatar answered Dec 08 '25 07:12

Boland


You should define a function in your component class:

getDiferenceInDays(theDate : Date) : number {
    return Math.abs(date.getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24) ;
}

and then use that in your template:

<td>
    <div *ngIf="getDiferenceInDays(todo.anyDate) > 50">fiffty</div>
</td>

Note that use can't use new in template expressions so you'll have to move your new Date() to the function part!

like image 23
KavehG Avatar answered Dec 08 '25 09:12

KavehG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!