Reputation: 2821
I am looking for a javascript function which will take one date value and tell me the next 30 days values.
For example, if the current date is 5 August 2011 I would want it to list all 30 days after this:
The function basically takes care of the month days (30 or 31 or 28 etc.)
Is this something I can solve easily? Thanks a lot for your help.
Upvotes: 3
Views: 4314
Reputation: 887453
You can use a for
loop and write new Date(year, month - 1, day + i)
.
The Javascript Date
constructor will normalize out-of-range dates to their proper values, so this will do exactly what you want.
You need to write month - 1
because months are zero-based.
Here's the code for this (JSFiddle):
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
var date = today.getDate();
for(var i=0; i<30; i++){
var day=new Date(year, month - 1, date + i);
console.log(day);
}
Upvotes: 12
Reputation: 27474
var date=new Date();
document.write(date);
document.write("<br>");
for (var x=0;x<40;++x)
{
var d=date.getDate();
date.setDate(d+1);
document.write(date);
document.write("<br>");
}
You want to use the built-in date functions. Don't try adding 24*60*60*1000 milliseconds to get to the next day. This assumes that every day is 24 hours long, which isn't true. Consider the days when daylight savings starts and ends.
Upvotes: 0
Reputation: 15370
If I'm understanding you correctly, then you might want something like this:
var nextXDays = function (days) {
var today = new Date();
var days = [];
var day_length = 1000 * 60 * 60 * 24; //the length of a day in milliseconds
for(var i = 0; i < days; i++) {
days.push(today + day_length*i);
}
}
var days = nextXDays(30); //return an array of the dates
Then, since you have an array of Date
objects, you can display them in any format that you like.
Upvotes: 0
Reputation: 4440
quick answer: use Date.js
. For example you could do new Date("today + 30 days");
and it will understand :] It's a pretty awesome library I use on a lot of projects for date kung-fu...
Upvotes: 2