Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS how to add days / months / years to a date [duplicate]

We are using AngularJS to set filters. Basically we have a start date and end date and frequency. When the frequency is set to week, we simply want to add 1 week to the start date, when the frequency is set to daily, we want to add 1 day to the start date.

Basically something like :-

var date = new date();

date.addDays(2);
date.addMonths(2);
date.addYears(2);
like image 294
Simon Avatar asked Jul 17 '14 14:07

Simon


People also ask

How to get date after 1 year in angular?

That way angular will get a regular JavaScript Date object instead of a moment instance and it's change detection will work correctly. To advance the year by 1. Use .setDate () function to increment the days and instead of +1 day and add +365 days it will give you date after 1 year.

How to change the datetime format in angular using MMM?

All types of datetime values displays the date in ‘MMM d, y’ format which is default Angular date format ‘mediumDate’. To change the datetime format in angular we have to pass date time format parameter to the angular pipe as shown below. { { date_value | date :'short'}} // 6/15/19, 5:24 PM.

How to add days to JavaScript date?

JavaScript provides the Date object which is used for manipulating date and time. In this tutorial, you will learn an easy way of adding days to Javascript Date with setDate () and getDate () inbuilt functions which are used to set and get the day of the month of the Date object. Here is a utility function which creates a Date copy:

What is short date format in angular?

The format ‘short’ is one of the predefined date formats in angular which converts our date value to ’M/d/yy, h:mm a’ format. List of all predefined date formats in Angular. Date Format. Angular datepipe code. Result.


1 Answers

I would consider using moment.js for all of your JS date related needs then you can do:

var date = moment();
date.add(2, 'days');
date.add(2, 'months');
date.add(2, 'years');

// or all of the above with:
date.add({years: 2, months: 2, days: 2});

And if you need a regular JS date object at the end, check out this post

like image 193
Brocco Avatar answered Sep 23 '22 14:09

Brocco