Link to home
Start Free TrialLog in
Avatar of mjw110
mjw110

asked on

JavaScript Dates


I currently have some Javascript code that picks out a range of dates in a list.  I would like to limit this to have a week prior and a week after today’s date.  Example:  if today’s date were 6 November 2002
6/11/2002 I would like to have all days before this date and all 7 days after.  Leaving me with a list like this.
30/10/02
31/10/02
1/11/02
2/11/02
3/11/02
4/11/02
5/11/02
6/11/02
7/11/02
8/11/02
9/11/02
10/11/02
11/11/02
12/11/02
13/11/02

Another problem I have is that the month of December or 12 appears as 0
An example is 1/0/02 instead of 1/12/02

This is the code I am currently using

<script language="JavaScript">
<!--
var now = new Date()
var aDay = 24*60*60*1000;
var then = new Date(now.getTime()+(31*aDay));
var text = '<select NAME="edtstart">';
for (i=(now.getTime()-(5*aDay));i<then.getTime();i+=aDay) {
  var date = new Date(i);
  var year = date.getYear();
  if (year < 1900) year += 1900;
  var dateString = (date.getDate()+1)+'/'+date.getMonth()+'/'+year;
  var USdateString = date.getMonth()+'/'+(date.getDate()+1)+'/'+year;
  text += '\n<option value="' + USdateString + '">'+ dateString+'</option>';
}
text += '</select>';
document.write(text);
//--></script>

I would appreciate any help
Avatar of knightEknight
knightEknight
Flag of United States of America image

in principle, you can achieve this by using the setDate function like this:


var today = new Date();
var dateString, text="";

for ( var i=-7; i<=7; i++ )
{
   dateString = "" + new Date( today.setDate(today.getDate()+i) );
   text += dateString + "\n";
}
oops, misplaced the  today  setting ...



var dateString, text="";

for ( var i=-7; i<=7; i++ )
{
  var today = new Date();
  dateString = "" + new Date( today.setDate(today.getDate()+i) );
  text += dateString + "\n";
}

alert(text);
I'll leave the formatting of each date to MM/DD/YYYY to you, since you already know that  :)
ASKER CERTIFIED SOLUTION
Avatar of gnrao
gnrao

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial