I am new to JavaScript (but not programming) and am having a difficult time figuring out where I made a mistake in this function, found here: http://mikeryan.webatu.com/function.html [dead link][Guessing of the original code at the bottom]
The function should take a DDMMYY timestamp and convert it into a human-readable string. For instance, 210710 would be turned into July 21st, 2010.
UPDATE: Code that is probably similar OP’s dead link:
function timestamp(d){
var year = (d-(Math.round(d / 100)*100);
var day = Math.floor(d/10000);
var dayfix = (day - (Math.floor(day/10)*10));
// var month = ((d-year)-(day*100000)/100);
var a = (d - year);
var b = ((day * 100000) / 10);
var month = (a - b) / 100;
var months = new Array();
months[1] = "January";
months[2] = "February";
months[3] = "March";
months[4] = "April";
months[5] = "May";
months[6] = "June";
months[7] = "July";
months[8] = "August";
months[9] = "September";
months[10] = "October";
months[11] = "November";
months[12] = "December";
var daysuffix = new Array();
daysuffix[0] = "th";
daysuffix[1] = "st";
daysuffix[2] = "nd";
daysuffix[3] = "rd";
daysuffix[4] = "th";
daysuffix[5] = "th";
daysuffix[6] = "th";
daysuffix[7] = "th";
daysuffix[8] = "th";
daysuffix[9] = "th";
if(year>20){
year = '19' + year;
}
else{
year = '20' + year;
}
return (months[month] + ' ' + day + daysuffix[dayfix] + ', ' + year);
}
One problem: you’re missing a parenthesis. Change:
to
That being said, this is a more straightforward calculation method:
Next, your array initialization is unnecessarily verbose. Instead of:
just do:
Your day suffix is incorrect. It puts “nd” after 12 and “12nd April” clearly isn’t correct. I would just use logic for doing this rather than a lookup array where most elements are “th”.
So:
Lastly there is little value in your “timestamp” being an integer in its present form. A more typical format for tis kind of thing is YYYYMMDD for two reasons:
Numerical ordering matches date ordering; and
It’s unambiguous. North Americans put month before day (ie MMDDYY). Everyone else in the world puts day first (ie DDMMYY). No one does YYDDMM.