Here is a date formatter that takes the string '20150415'
and returns the string 'April 4, 2015'
. You can adjust the date format to your liking by modifying the last line of DateFormat.toLong
.
var DateFormat = {
months: ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'],
toLong: function toLongDate(s) { // s is a string like '20150415'
var year = parseInt(s.substring(0, 4), 10),
month = DateFormat.months[parseInt(s.substring(4, 6), 10) - 1],
day = parseInt(s.substring(6), 10);
return month + ' ' + day + ', ' + year;
}
};
// A small test.
alert(DateFormat.toLong('20150415'));
Note that I am passing the second argument to parseInt
to indicate that the number represented by the string is in base 10. If you don't specify base 10, strings starting with the numeral 0 may be parsed as though they were in base 8.
You can read about this in the JavaScript documentation on the Mozilla Developer Network:
If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.