Chris
Chris

Reputation: 4728

Angular2 date formatting and add one day

I have a date in YYYY-MM-DD format - this is defined as this.queryDate. This is set to 2017-04-05

I would like to show two buttons in my system. The first show the date in the format 5th April 2017. The second button should be the following day.

actionSheet.addButton({text: this.queryDate });        
actionSheet.addButton({text: [this.queryDate + 1 day] }); 

I am unsure how to change the date format and then add 24 hours to my start date. I am new to Angular 2 but this is how I would achieve it using PHP. This is my ugly Angular2 + PHP mongrel code ..

actionSheet.addButton({text: date("jS M Y", strtotime(this.queryDate)) });               
actionSheet.addButton({text: date("jS M Y", strtotime(this.queryDate)+(60*60*24)) });               

How can I achieve this in Angular 2?

Upvotes: 1

Views: 10728

Answers (2)

Vojtech
Vojtech

Reputation: 2816

I recommend using Moment.js for the date manipulation. It provides a wrapper for the native JavaScript date object. In doing this, Moment.js extends the functionality and also accounts for several deficiencies in the object.

moment().add(1, 'days').format('D MMMM YYYY');    

You can even use the calendar output and it will handle things like today, tomorrow,... for you.

https://momentjs.com/docs/#/displaying/calendar-time/

In case you do not have moment included in your project and do not want to add a big dependency. There are alternatives like date fns.

https://date-fns.org/v1.29.0/docs/addDays

Upvotes: 0

Adam
Adam

Reputation: 4683

Your code is pretty similar to how it works in JavaScript.

new Date((new Date(this.queryDate)).getTime() + (60*60*24*1000));

And to combine it with your code:

actionSheet.addButton({text: new Date((new Date(this.queryDate)).getTime() + (60*60*24*1000)) }); 

To explain, new Date('1990 04 03') parses your date string into a new date variable. .getTime() gets the time as a timestamp (number of MS from midnight Jan 1, 1980 (I think). Then you add 1 day, in milliseconds. Finally, new Date(...); parses your number back into a date.

You might notice that your date doesn't parse correctly, if it's in the format YYYY-MM-DD. When I tried it out, it was several hours off the time I expected it to be, because it's giving me the time in GMT, not my timezone, but if I gave it the date in the format YYYY MM DD, it would do it in my timezone. The default date parsing tools aren't the best in JS, unfortunately.

If you want to use a specific timezone, I would recommend using something like moment.js to parse the date, since it's much more robust.

You can learn more about JS date parsing here.

Edit

I also forgot to mention, there's no easy way to output a date in JS in a specific format, so you may have it to craft it yourself using getDate(), getMonth(), and getFullYear(). If you do choose to use moment.js, they do have functionality for easier date formatting.

Upvotes: 3

Related Questions