Join Bytes! (Luis) writes:
[color=blue]
> I've adapted the following code so that it prints the date in
> DD/MM/YYYY format. However it prints the incorrect date! If todays
> date is 01/01/2003 it prints 03/01/2003 - 3 days out! What have I done
> wrong?[/color]
A few problems:
[color=blue]
> CalendarDay = aCalendar.getDay();[/color]
You probably don't need getDay. It returns the number of the day in
the week, not the day in the month.
[color=blue]
> CalendarYear = aCalendar.getYear();[/color]
You might want to use getFullYear if it exists.
[color=blue]
> var dayname = new Array ("01", "02", "03", "04", "05", "06", "07",
> "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18",
> "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29",
> "30", "31" );[/color]
with this definition, dayname[1]=="02".
The date object getDate returns the date, and your array is one off,
since it starts at index zero.
Notice that the getMonth method returns the month number minus one,
so January is month zero. Your month array works correctly.
[color=blue]
> if (CalendarDate < 10) MonthSize=("0" + CalendarMonth + "/");
> else MonthSize=(CalendarDate + "/");[/color]
If the date is <10 you add a zero in front of the month, else not
in front of the date???
Later, you don't use MonthSize at all.
[color=blue]
> if (CalendarDate < 10) DaySize=("0" + CalendarDay + "/");
> else DaySize=(CalendarDate + "/");[/color]
You use Day and Date interchangably. Today is the third, so Date is 3.
It is a Friday, so Day is 5.
Again, you don't use DaySize at all.
[color=blue]
> var TheDateIs = dayname[CalendarDay] + "/" + monthname[CalendarMonth]
> + "/" + CalendarYear[/color]
So this is where you look up the dayname (where you mean datename) by
the week day and one off.
Try this:
---
var aCalendar = new Date();
var theDate = aCalendar.getDate();
if (theDate < 10) {theDate = "0"+theDate;}
var theMonth = aCalendar.getMonth();
if (theMonth<10) {theMonth = "0"+theMonth;}
var theYear;
if (aCalendar.getFullYear) {
theYear = aCalendar.getFullYear(); // use getFullYear if it exists
} else {
theYear = aCalendar.getYear(); // use getYear, add 1900 depending on browser
if (theYear<1900) {
theYear += 1900;
}
}
var TheDateIs = theDate+"/"+theMonth+"/"+theYear;
---
You should seriously consider another format for the date. Neither
dd/mm/yyyy nor mm/dd/yyyy are universally understandable. In an
international setting like the internet, yyyy/mm/dd is much safer.
/L
--
Lasse Reichstein Nielsen -
Join Bytes!
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'