How to add days to a date in Angular2? [duplicate]
Asked Answered
T

1

25

I simply want to create a date that is 3 days from now for use in a typescript angular component.

I have looked at Angular2 moment but this seems only to relate to pipes. Although I did see this article about using pipes in code, looks a bit hacky...

Maybe I'm missing something as this should be really simple?!

Thanks

Tachycardia answered 22/9, 2017 at 16:10 Comment(6)
Dates are outside of the concern of Angular or even TypeScript. You can use the built in javascript Date object or use moment.js directly.Storey
Is this only for display or do you want to do something else with the later date?Anglican
Thanks - yes msanford I want to use it not just for display. OK seems I'm barking up the wrong tree and I need to just use the JavaScript Date.Tachycardia
... I need to just use the JavaScript Date <= I prefer moment.js, it's more flexible in many situations and widely supported in many other apis. This is just personal preference though.Storey
Cool - yes I have used moment in the distant past - seems to be the defacto library for this kind of requirement.Tachycardia
new Date((new Date()).getTime() + (60*60*24*1000*numberOfDays))Emmyemmye
R
59
date: Date;

ngOnInit() {
  this.date = new Date();
  this.date.setDate( this.date.getDate() + 3 );
}

Then you can use the date pipe to display the date nicely in your HTML

{{ date | date }}

Which renders thusly:

Sep 25, 2017

Regardless answered 22/9, 2017 at 17:17 Comment(2)
But this is not working with daylight saving time countries. How to get correct dates in other countries?Hazardous
This does not work when date is before current date, i.e., some months earlier. Can you suggest another way?Osteoplastic

© 2022 - 2024 — McMap. All rights reserved.