我注意到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()对象支持的格式说明符的文档在哪里?


当前回答

sugar.js库有一些很棒的功能,可以在JavaScript中处理日期。它有很好的记录。

Sugar从Date.create开始就给了Date类很多爱可以理解15大调任何格式的日期的方法语言,包括“1小时前”等相对格式。日期可以也可以使用易于理解的语言以任何格式或语言输出语法,以及常用日期格式的快捷方式。复杂日期与is这样的方法进行比较也是可能的,它可以理解任何格式和应用内置精度。

几个例子:

Date.create('July 4, 1776')  -> July 4, 1776
Date.create(-446806800000)   -> November 5, 1955
Date.create(1776, 6, 4)      -> July 4, 1776
Date.create('1776年07月04日', 'ja') -> July 4, 1776
Date.utc.create('July 4, 1776', 'en')  -> July 4, 1776

Date.create().format('{Weekday} {d} {Month}, {yyyy}')    -> Monday July 4, 2003
Date.create().format('{hh}:{mm}')                        -> 15:57
Date.create().format('{12hr}:{mm}{tt}')                  -> 3:57pm
Date.create().format(Date.ISO8601_DATETIME)              -> 2011-07-05 12:24:55.528Z

Date.create().is('the 7th of June') -> false
Date.create().addMonths(2); ->"Sunday, June 15, 2014 13:39"

其他回答

自定义格式设置函数:

对于固定格式,一个简单的函数即可完成任务。以下示例生成国际格式YYYY-MM-DD:

function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

注意:然而,扩展Javascript标准库通常不是一个好主意(例如,通过将此函数添加到Date的原型中)。

更高级的功能可以基于格式参数生成可配置的输出。在同一页中有几个很好的例子。

如果编写一个格式化函数太长,那么周围有很多库可以执行它。其他一些答案已经列举了它们。但日益增加的依赖性也有反作用。

标准ECMAScript格式化函数:

自从ECMAscript的最新版本以来,Date类具有一些特定的格式化函数:

toDateString:依赖于实现,仅显示日期。http://www.ecma-international.org/ecma-262/7.0/index.html#sec-日期.协议类型.日期new Date().toDateString();//例如“2016年11月11日星期五”


toISOString:显示ISO 8601日期和时间。http://www.ecma-international.org/ecma-262/7.0/index.html#sec-日期.协议类型.toisostringnew Date().toISOString();//例如“2016-11-21T08:00:00.000Z”


toJSON:JSON的Stringer。http://www.ecma-international.org/ecma-262/7.0/index.html#sec-日期.原型.项目new Date().toJSON();//例如“2016-11-21T08:00:00.000Z”


toLocaleDateString:依赖于实现,区域设置格式的日期。http://www.ecma-international.org/ecma-262/7.0/index.html#sec-日期.协议类型.颜色日期字符串new Date().toLocaleDateString();//例如“2016年11月21日”


toLocaleString:依赖于实现,是区域设置格式的日期和时间。http://www.ecma-international.org/ecma-262/7.0/index.html#sec-日期.协议类型.颜色字符串new Date().toLocaleString();//例如“2016年11月21日上午08:00:00”


toLocaleTimeString:依赖于实现,以区域设置格式表示时间。http://www.ecma-international.org/ecma-262/7.0/index.html#sec-日期.协议类型.颜色时间字符串new Date().toLocaleTimeString();//例如“08:00:00 AM”


toString:日期的通用toString。http://www.ecma-international.org/ecma-262/7.0/index.html#sec-日期.协议类型.测试new Date().toString();//例如“2016年11月11日星期五08:00:00 GMT+0100(西欧标准时间)”

注意:可以使用这些格式化函数生成自定义输出:

new Date().toISOString().slice(0,10); // By @Image72, return YYYY-MM-DD

我喜欢使用JavaScript和使用日期来格式化时间和日期的10种方法。

基本上,您有三种方法,必须自己组合字符串:

getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year

例子:

var d=新日期();var curr_date=d.getDate();var curr_month=d.getMonth()+1//月份为零var curr_year=d.getFullYear();console.log(curr_date+“-”+curr_month+“-“+curr_year);

如果您希望只显示两位数的时间,这可能会帮助您:

var now = new Date();
var cHour = now.getHours();
var cMinuts = now.getMinutes();
var cSeconds = now.getSeconds();

var outStr = (cHour <= 0 ? ('0' + cHour) : cHour) + ':' + (cMinuts <= 9 ? ('0' + cMinuts) : cMinuts) + ':' + (cSeconds <= 9 ? '0' + cSeconds : cSeconds);

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

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

此代码不起作用:

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

您可以使用meiz所指出的新格式方法来扩展Date对象,下面是作者给出的代码。和这是一把小提琴。

Date.prototype.format = function(format) //author: meizz
{
  var o = {
    "M+" : this.getMonth()+1, //month
    "d+" : this.getDate(),    //day
    "h+" : this.getHours(),   //hour
    "m+" : this.getMinutes(), //minute
    "s+" : this.getSeconds(), //second
    "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
    "S" : this.getMilliseconds() //millisecond
  }

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

alert(new Date().format("yyyy-MM-dd"));
alert(new Date("january 12 2008 11:12:30").format("yyyy-MM-dd h:mm:ss"));