我注意到JavaScript的新Date()函数在接受多种格式的日期方面非常聪明。

Xmas95 = new Date("25 Dec, 1995 23:15:00")
Xmas95 = new Date("2009 06 12,12:52:39")
Xmas95 = new Date("20 09 2006,12:52:39")

调用new Date()函数时,我在任何地方都找不到显示所有有效字符串格式的文档。

这用于将字符串转换为日期。如果我们从相反的方面来看,即将日期对象转换为字符串,直到现在,我的印象是JavaScript没有将日期对象格式化为字符串的内置API。

编者按:以下方法是询问者在特定浏览器上的尝试,但通常不起作用;请参阅本页上的答案以了解一些实际解决方案。

今天,我在date对象上使用了toString()方法,令人惊讶的是,它可以将日期格式化为字符串。

var d1 = new Date();
d1.toString('yyyy-MM-dd');       //Returns "2009-06-29" in Internet Explorer, but not Firefox or Chrome
d1.toString('dddd, MMMM ,yyyy')  //Returns "Monday, June 29,2009" in Internet Explorer, but not Firefox or Chrome

在这里,我也找不到任何关于将日期对象格式化为字符串的方法的文档。

列出Date()对象支持的格式说明符的文档在哪里?


当前回答

只是为了继续龚志涛的坚定回答-这处理上午/下午

 Date.prototype.format = function (format) //author: meizz
{
    var hours = this.getHours();
    var ttime = "AM";
    if(format.indexOf("t") > -1 && hours > 12)
    {
        hours = hours - 12;
        ttime = "PM";
     }

var o = {
    "M+": this.getMonth() + 1, //month
    "d+": this.getDate(),    //day
    "h+": hours,   //hour
    "m+": this.getMinutes(), //minute
    "s+": this.getSeconds(), //second
    "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
    "S": this.getMilliseconds(), //millisecond,
    "t+": ttime
}

if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
  (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o) if (new RegExp("(" + k + ")").test(format))
    format = format.replace(RegExp.$1,
      RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length));
return format;
}

其他回答

如果您已经在项目中使用jQuery UI,则可以使用内置日期选择器方法格式化日期对象:

$.datepicker.formatDate('yy-mm-dd', new Date(2007, 1 - 1, 26));

但是,日期选择器仅设置日期格式,而不能设置时间格式。

查看jQueryUI日期选择器formatDate示例。

使用此函数

toTimeString() and toLocaleDateString()

有关详细信息,请参阅下面的链接https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

设置日期格式以返回“2012-12-29”的正确方法是使用JavaScript日期格式中的脚本:

var d1 = new Date();
return d1.format("dd-m-yy");

此代码不起作用:

var d1 = new Date();
d1.toString('yyyy-MM-dd');      

在JavaScript中格式化,尤其是解析日期可能有点头疼。并非所有浏览器都以相同的方式处理日期。因此,虽然了解基本方法很有用,但使用助手库更实用。

Adam Shaw的XDate javascript库自2011年年中就已经问世,目前仍在积极开发中。它有很棒的文档,很棒的API,格式化,试图保持向后兼容,甚至支持本地化字符串。

更改区域设置字符串的链接:https://gist.github.com/1221376

许多框架(您可能已经在使用)具有您可能不知道的日期格式。jQueryUI已经被提及,但其他框架如Kendo UI(全球化)、Yahoo UI(Util)和AngularJS也有。

// 11/6/2000
kendo.toString(new Date(value), "d")

// Monday, November 06, 2000
kendo.toString(new Date(2000, 10, 6), "D")