开发者

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 a开发者_开发知识库m new to javascript so examples would be helpful.

EDITED

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


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.


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


try

new Date(+yourDate - 30 *86400000)

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

console.log(newDate)


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜