Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 30 days to date (mm/dd/yy)

I have a date in the format mm/dd/yy and want to add 30 days to it. I am just curious the best method to do this? I am new to javascript so examples would be helpful.

EDITED

Sorry I am using US date format mm/dd/yy.

like image 595
Jim Avatar asked May 08 '11 22:05

Jim


People also ask

How do you add 30 days in a moment?

Just import moment in your file and invoke moment(). add(30, 'days'); it will show the current date time plus 30 days. moment().

How do I add days to a date format?

Using the DATE Function The DATE function can add days to a date in Excel. The DATE function returns the date in the m/dd/yyyy format by taking one argument each for the year, month and day. Including the DAY function will do the trick here as it will be used to add the number of days.

How can I get 30 days from date in PHP?

echo date('m/d/Y',strtotime('+30 days',strtotime('05/06/2016'))) . PHP_EOL; This will return 06/06/2016 . Am assuming your initial date was in m/d/Y format.


2 Answers

A simple way to get it done is to send the timestamp value in the Date constructor. To calculate 30 days measured in timestamp:

30 * 24 * 60 * 60 * 1000

Then, you need the current timestamp:

Date.now()

Finally, sum both values and send the result as a param in the constructor:

var nowPlus30Days = new Date(Date.now() + (30 * 24 * 60 * 60 * 1000));

like image 21
Alberto Mendoza Avatar answered Sep 27 '22 00:09

Alberto Mendoza


Updated answer (2018)

One way to add 30 days to a date string is to parse it to a Date, add 30 days, then format it back to a string.

Date strings should be parsed manually, either with a bespoke function or a library. Either way, you need to know the format to know if it's been parsed correctly, e.g.

// Given a string in m/d/y format, return a Date
function parseMDY(s) {
  var b = s.split(/\D/);
  return new Date(b[2], b[0]-1, b[1]);
}

// Given a Date, return a string in m/d/y format
function formatMDY(d) {
  function z(n){return (n<10?'0':'')+n}
  if (isNaN(+d)) return d.toString();
  return z(d.getMonth()+1) + '/' + z(d.getDate()) + '/' + d.getFullYear();
}

// Given a string in m/d/y format, return a string in the same format with n days added
function addDays(s, days) {
  var d = parseMDY(s);
  d.setDate(d.getDate() + Number(days));
  return formatMDY(d);
}

[['6/30/2018', 30],
 ['1/30/2018', 30], // Goes from 30 Jan to 1 Mar
 ['12/31/2019', 30]].forEach(a => {
  console.log(`${a[0]} => ${addDays(...a)}`);
});

If the "30 days" criterion is interpreted as adding a month, that is a bit trickier. Adding 1 month to 31 January will give 31 February, which resolves to 2 or 3 March depending on whether February for that year has 28 or 29 days. One algorithm to resolve that is to see if the month has gone too far and set the date to the last day of the previous month, so 2018-01-31 plus one month gives 2018-02-28.

The same algorithm works for subtracting months, e.g.

/**
 * @param {Date} date - date to add months to
 * @param {number} months - months to add
 * @returns {Date}
*/
function addMonths(date, months) {

  // Deal with invalid Date
  if (isNaN(+date)) return;
  
  months = parseInt(months);

  // Deal with months not being a number
  if (isNaN(months)) return;

  // Store date's current month
  var m = date.getMonth();
  date.setMonth(date.getMonth() + months);
  
  // Check new month, if rolled over an extra month, 
  // go back to last day of previous month
  if (date.getMonth() != (m + 12 + months)%12) {
    date.setDate(0);
  }
  
  // date is modified in place, but return for convenience
  return date;
}

// Helper to format the date as D-MMM-YYYY
// using browser default language
function formatDMMMY(date) {
  var month = date.toLocaleString(undefined,{month:'short'});
  return date.getDate() + '-' + month + '-' + date.getFullYear();
}

// Some tests
[[new Date(2018,0,31),  1],
 [new Date(2017,11,31), 2],
 [new Date(2018,2,31), -1],
 [new Date(2018,6,31), -1],
 [new Date(2018,6,31), -17]].forEach(a => {
   let f = formatDMMMY;
   console.log(`${f(a[0])} plus ${a[1]} months: ${f(addMonths(...a))}`); 
});

Of course a library can help with the above, the algorithms are the same.

Original answer (very much out of date now)

Simply add 30 days to todays date:

var now = new Date();
now.setDate(now.getDate() + 30);

However, is that what you really want to do? Or do you want to get today plus one month?

You can convert a d/m/y date to a date object using:

var dString = '9/5/2011';
var dParts = dString.split('/');
var in30Days = new Date(dParts[2] + '/' +
                        dParts[1] + '/' +
                        (+dParts[0] + 30)
               );

For US date format, swap parts 0 and 1:

var in30Days = new Date(dParts[2] + '/' +
                        dParts[0] + '/' +
                        (+dParts[1] + 30)
               );

But it is better to get the date into an ISO8601 format before giving it to the function, you really shouldn't be mixing date parsing and arithmetic in the same function. A comprehensive date parsing function is complex (not excessively but they are tediously long and need lots of testing), arithmetic is quite simple once you have a date object.

like image 163
RobG Avatar answered Sep 25 '22 00:09

RobG