Javascript简单的日期转换

时间:2013-10-04 11:00:10

标签: javascript

我正在寻找一种轻松的方法,使以下日期格式更具可读性。

04OCT2013

我最好还是输出:

4 October 2013

非常感谢任何帮助,谢谢!

6 个答案:

答案 0 :(得分:1)

首先需要解析字符串,然后格式化它的各个部分。您可以使用一些完整的库(there are a few),或者自己编写两个简单的函数:

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"

答案 1 :(得分:1)

灵感来自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

答案 2 :(得分:0)

您可以尝试使用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);

Js Fiddle Demo

答案 3 :(得分:0)

 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。

答案 4 :(得分:0)

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);

答案 5 :(得分:0)

Jsut格式化字符串并使用内置的Date type和解析:

var myString = "04OCT2013";

然后将第一个字符和最后4个月和月份进行子串,这样就可以使用内置的解析器,如下所示:

Date.parse("Aug 9, 1995");

无需创建自己的月份数组。