Victor
Victor

Reputation: 1271

Javascript - Set date 30 days from now

I need to set a date that would be 30 days from now taking into account months that are 28,29,30,31 days so it doesn't skip any days and shows exactly 30 days from now. How can I do that?

Upvotes: 14

Views: 51195

Answers (8)

Ibra Him
Ibra Him

Reputation: 1

const afterMonth = new Date(new Date().setDate(new Date().getDate()+30)).toISOString()

const Now = new Date().toISOString()

Upvotes: 0

zemunkh
zemunkh

Reputation: 712

const today = new Date();    
const thirty_days_from_now = new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000),

Upvotes: 0

Ron Kinkade
Ron Kinkade

Reputation: 11

I've been able to make this work:

function() {
// Get local time as ISO string with offset at the end
var now = new Date();
now.setMonth(now.getMonth() + 1);
var pad = function(num) {
    var norm = Math.abs(Math.floor(num));
    return (norm < 10 ? '0' : '') + norm;
};
return now.getFullYear() 
    + '-' + pad(now.getMonth()+1)
    + '-' + pad(now.getDate());
}

Upvotes: -1

nurealam siddiq
nurealam siddiq

Reputation: 1623

Try this piece of code:

const date = new Date();
futureDate = new Date(date.setDate(date.getDate() + 30)).toLocaleDateString();

Upvotes: 1

Rich Apodaca
Rich Apodaca

Reputation: 29004

Using the native Date object with straightforward syntax and no external libraries:

var future = new Date('Jan 1, 2014');

future.setTime(future.getTime() + 30 * 24 * 60 * 60 * 1000); // Jan 31, 2014

The Date setTime and getTime functions use milliseconds since Jan 1, 1970 (link).

Upvotes: 8

timrwood
timrwood

Reputation: 10671

I wrote a Date wrapper library that helps with parsing, manipulating, and formatting dates.

https://github.com/timrwood/moment

Here is how you would do it with Moment.js

var inThirtyDays = moment().add('days', 30);

Upvotes: 7

Domenic
Domenic

Reputation: 112807

var now = new Date();
var THIRTY_DAYS = 30 * 24 * 60 * 60 * 1000;
var thirtyDaysFromNow = now + THIRTY_DAYS;

Upvotes: 4

Pointy
Pointy

Reputation: 413682

The JavaScript "Date()" object has got you covered:

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

That'll just do the right thing. (It's a little confusing that the getter/setters for day-of-month have the names they do.)

Upvotes: 47

Related Questions