Transform this date formatter which converts the string value '20150415'
into 'April 4, 2015'
. Customize the date format by adjusting the last line of the DateFormat.toLong
function.
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 quick test.
alert(DateFormat.toLong('20150415'));
Remember to specify a radix when using parseInt to avoid misinterpretations based on the input string. Failure to do so may lead to parsing strings starting with '0' as octal instead of decimal. More information is available in the JavaScript documentation on the Mozilla Developer Network:
If the input string begins with "0", the radix is either eight (octal) or ten (decimal), which can vary depending on the implementation. While ECMAScript 5 specifies the use of 10 (decimal), not all browsers fully support this yet. Therefore, it is advisable to always specify a radix when utilizing parseInt.