我正在寻找一种使以下日期格式更具可读性的轻量级方法。
04OCT2013
理想情况下,我希望它输出:
4 October 2013
任何帮助将不胜感激,谢谢!
您首先需要解析您的字符串,然后格式化它的各个部分。您可以为此使用一些成熟的库(有一些),或者自己编写两个简单的函数:
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"
灵感来自 Bergi 的回答:
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
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();
但我会建议 date.js 甚至更好的 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 稍微格式化字符串并使用内置的Date 类型和 parse :
var myString = "04OCT2013";
然后子串出第一个字符,最后 4 个和月份,这样你就可以使用内置的解析器,如下所示:
Date.parse("Aug 9, 1995");
无需创建自己的月份数组。