我有这个:
Start Date: <input type="date" id="startDate" name="startDate" ></p>
var mydate = new Date(form.startDate.value);
之后,mydate变为
"05/05/2010"
现在,我想将此格式更改为
May 2010
有没有办法在JavaScript中执行此操作?
答案 0 :(得分:37)
你当然可以自己格式化日期..
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示例:
<script src="http://www.datejs.com/build/date.js" type="text/javascript"></script>
<script>
var mydate = new Date(form.startDate.value);
var str = mydate.toString("MMMM yyyy");
window.alert(str);
</script>
答案 1 :(得分:11)
使用Datejs库,这可以很简单:
Date.parse("05/05/2010").toString("MMMM yyyy");
// parse date convert to
// string with
// custom format
答案 2 :(得分:5)
var month = mydate.getMonth(); // month (in integer 0-11)
var year = mydate.getFullYear(); // year
然后您需要拥有的是几个月的数组:
var months = ['Jan', 'Feb', 'Mar', ...];
然后展示它:
alert(months[month] + " " + year);
答案 3 :(得分:2)
尝试 -
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();
答案 4 :(得分:1)
使用你的mydate对象并调用getMonth()和getFullYear()
有关详情,请参阅此处: http://www.w3schools.com/jsref/jsref_obj_date.asp