我注意到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"

其他回答

答案是“无处”,因为日期格式是专有功能。我不认为toString函数要符合特定的格式。例如在ECMAScript 5.1规范中(http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf,2013年2月8日,第173页),toString函数记录如下:

“字符串的内容取决于实现”

下面的示例等函数可以很容易地完成格式化。

function pad(toPad, padWith) {
    return (String(padWith) + String(toPad)).slice(-1 * padWith.length);
}

function dateAsInputValue(toFormat) {
    if(!(toFormat instanceof Date)) return null;
    return toFormat.getFullYear() + "-" + pad(toFormat.getMonth() + 1, "00") + "-" + pad(toFormat.getDate(), "00");
}

function timeAsInputValue(toFormat) {
    if(!(toFormat instanceof Date)) return null;        
    return pad(toFormat.getHours(), "00") + ":" + pad(toFormat.getMinutes(), "00") + ":" + pad(toFormat.getSeconds(), "00");
}

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

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

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

我做了一个非常简单的格式化程序,它是cut/n/postable(更新了更整洁的版本):

function DateFmt(fstr) {
  this.formatString = fstr

  var mthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  var dayNames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
  var zeroPad = function(number) {
     return ("0"+number).substr(-2,2);
  }

  var dateMarkers = {
    d:['getDate',function(v) { return zeroPad(v)}],
    m:['getMonth',function(v) { return zeroPad(v+1)}],
    n:['getMonth',function(v) { return mthNames[v]; }],
    w:['getDay',function(v) { return dayNames[v]; }],
    y:['getFullYear'],
    H:['getHours',function(v) { return zeroPad(v)}],
    M:['getMinutes',function(v) { return zeroPad(v)}],
    S:['getSeconds',function(v) { return zeroPad(v)}],
    i:['toISOString']
  };

  this.format = function(date) {
    var dateTxt = this.formatString.replace(/%(.)/g, function(m, p) {
      var rv = date[(dateMarkers[p])[0]]()

      if ( dateMarkers[p][1] != null ) rv = dateMarkers[p][1](rv)

      return rv

    });

    return dateTxt
  }

}

fmt = new DateFmt("%w %d:%n:%y - %H:%M:%S  %i")
v = fmt.format(new Date())

http://snipplr.com/view/66968.82825/

我喜欢使用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);

这个问题的具体答案在以下两行中找到:

//拉今年的最后两位数console.log(newDate().getFullYear().toString().substr(2,2));

格式化完整日期时间示例(MMddyy):jsFiddle

JavaScript:

//将日期格式化为MMddyy的函数函数格式日期(d){//得到这个月var month=d.getMonth();//把握好这一天var day=d.getDate();//获得年度最佳成绩var year=d.getFullYear();//拉今年的最后两位数year=year.toString().substr(2,2);//由于索引为0,每月递增1月=月+1;//将月份转换为字符串月=月+“”;//如果月份是1-9,请用0向右填充两位数如果(月长度==1){月=“0”+月;}//将日期转换为字符串day=天+“”;//如果日期在1-9之间,则用0表示两位数如果(日长度==1){天=“0”+天;}//返回字符串“MMddyy”回归月+日+年;}var d=新日期();console.log(formatDate(d));