I'm looking for a lightweight way of making the following date format more readable.
04OCT2013
I would ideally like to it output:
4 October 2013
Any help would be really appreciated, thanks!
I'm looking for a lightweight way of making the following date format more readable.
04OCT2013
I would ideally like to it output:
4 October 2013
Any help would be really appreciated, thanks!
You first will need to parse your string, then format the parts of it. You can use some full-fledged libary for this (there are a few), or write the two simple functions yourself:
var shortMonths = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dez"],
longMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function parse(datestring) {
var date = parseInt(datestring.slice(0,2), 10),
month = shortMonths.indexOf(datestring.slice(2,5).toLowerCase()),
year = parseInt(datestring.slice(5,9), 10);
return new Date(year, month, date);
}
function format(date) {
return [date.getDate(), longMonths[date.getMonth()], date.getFullYear()].join(" ");
}
> format(parse("04OCT2013"))
"4 October 2013"
Inspired by Bergi's answer:
function formatDate(s) {
s = s.toLowerCase().match(/\d+|\D+/g);
var months = {jan:'January', feb:'February', mar:'March', apr:'April',
may:'May', jun:'June', jul:'July', aug:'August', sep:'September',
oct:'October', nov:'November', dec:'December'};
return +s[0] + ' ' + months[s[1]] + ' ' + s[2];
}
formatDate('04OCT2013'); // 4 October 2013
formatDate('14NOV2015'); // 14 November 2015
You can try with moment.js
<script src="//cdn.jsdelivr.net/momentjs/2.0.0/moment.min.js"></script>
var date = new Date("04OCT2013");
var newDate = moment(date).format("DD MMMM YYYY");
alert(newDate);
var months= [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
var d = new Date();
var desc = d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear();
But I would suggest date.js or even better moment.js.
var now = new Date();
var monthNamesL = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ],
monthNamesS = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var dateFmtd = monthNamesL[now.getMonth()] + ' ' + now.getDay() + ', ' + now.getFullYear();
alert(dateFmtd);
Jsut format the string a bit and use the built in Date type with parse :
var myString = "04OCT2013";
then substring out the first characters, and the last 4 and the month so you can use the built in parser like below :
Date.parse("Aug 9, 1995");
No need to create your own arrays of months.