关于日期时间:如何在javascript中更改日期格式

How to change date format in JavaScript

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Formatting a date in javascript

我有这个:

HTML

1
2
Start Date:  <input type="date" id="startDate" name="startDate">
</p>

JavaScript

1
var  mydate = new Date(form.startDate.value);

在那之后我的日期变成

1
"05/05/2010"

现在,我想将此格式更改为

1
May 2010

有没有用JavaScript实现的方法?


你当然可以自己安排日期。

1
2
3
4
var mydate = new Date(form.startDate.value);
var month = ["January","February","March","April","May","June",
"July","August","September","October","November","December"][mydate.getMonth()];
var str = month + ' ' + mydate.getFullYear();

您还可以使用外部库,如datejs。

下面是一个datejs示例:

1
2
3
4
5
<script src="http://www.datejs.com/build/date.js" type="text/javascript">

   var mydate = new Date(form.startDate.value);
   var str = mydate.toString("MMMM yyyy");
   window.alert(str);

使用DateJS库,这可以简单到:

1
2
3
4
Date.parse("05/05/2010").toString("MMMM yyyy");
//          parse date             convert to
//                                 string with
//                                 custom format


1
2
var month = mydate.getMonth(); // month (in integer 0-11)
var year = mydate.getFullYear(); // year

那么你所需要的就是一系列的月份:

1
var months = ['Jan', 'Feb', 'Mar', ...];

然后展示:

1
alert(months[month] +" " + year);

尝试-

1
2
3
4
5
var monthNames = ["January","February","March","April","May","June",
   "July","August","September","October","November","December" ];

var newDate = new Date(form.startDate.value);
var formattedDate = monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear();

使用myDate对象并调用getMonth()和getFullYear()。

更多信息请参见:http://www.w3schools.com/jsref/jsref_obj_date.asp