19

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.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Jim
  • 227
  • 1
  • 3
  • 6

4 Answers4

43

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • You'd need to do a bit more work to create the Date object using the non-US date format in the question. – Phil May 08 '11 at 22:49
  • No, I don't. The above builds an ISO8601 format date string, which the ECMAScript Date object parses by default. There was a small error in the original unrelated to the format, but I've edited that since. :-) – RobG May 08 '11 at 22:59
  • @RobG I meant parsing the non-US date string for setting the initial Date object time (*ed: looks like you got what I meant*) ;-) – Phil May 08 '11 at 23:00
  • @Jim In that case, simply pass your datestring into the `Date` constructor – Phil May 08 '11 at 23:04
  • @Phil - Could you please give an example – Jim May 08 '11 at 23:22
  • @Jim `var ds = "9/5/2011"; var d = new Date(ds);` – Phil May 08 '11 at 23:28
  • @RobG Just curious, what do you mean by "plus one month"? That seems rather ambiguous. What is Jan. 31st plus one month? – rob May 08 '11 at 23:56
  • @Rob—that's why I asked. If you simply add one to the month, you may go from 31 Jan to 3 Mar. Logic for such cases likely differs depending on the requirement. – RobG Jul 12 '12 at 06:42
  • @Jim—please do not encourage using the Date object to parse strings, that format not part of the ECMAScript standard and is not supported by all browsers. The only reliable way to deal with string dates is to manually parse them, at least until support for [ES5's modified ISO8601 long format](http://es5.github.com/#x15.9.1.15) is ubiquitous. Note that in ECMAScript ed 3, parsing was not standardised at all, it was completely implementation dependent. – RobG Jul 12 '12 at 06:45
  • I don't think the getDate() + 30 concept works for instances where the days being added to it is not today. The function getDate() only returns the day of the month. For example, if you are a adding 30 days to a Date during the following month, it assumes you are in the current month... – geekinit Jul 18 '13 at 17:13
  • @geekinit—the first example uses the current date for convenience, the subsequent code uses, and works with, any date object. – RobG Jul 19 '13 at 04:51
16

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));

Alberto Mendoza
  • 169
  • 1
  • 5
  • var nowPlus30Days = new Date(Date.now() + 30*24*60*60*1000).toJSON().slice(0,10); – Weihui Guo Jul 10 '16 at 01:54
  • 3
    This doesn't work reliably over daylight saving boundaries as not all days are 24 hours long. Far better to use `date.setDate(date.getDate() + 30)`, which is also less to type. :-) – RobG Oct 30 '18 at 01:18
0

try

new Date(+yourDate - 30 *86400000)

var yourDate = new Date() 
var newDate = new Date(+yourDate - 30 *86400000)

console.log(newDate)
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

React Answer

Some of the Javascript commands are not available in React like getDate(). Also, I find it better to change dates to Unix timestamps so I can compare dates more easily in database searches using a simple mathematical greater than search.

const nowPlus30Days = new Date(Date.now() + (30 * 24 * 60 * 60 * 1000)).getTime() / 1000; 
(1597829050.184)

I can compare this to today:

const today = new Date().getTime() / 1000 
(1595237050.184)
David White
  • 621
  • 1
  • 10
  • 23