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


当前回答

我找不到任何关于有效日期格式的权威文档,所以我编写了自己的测试,看看各种浏览器支持什么。

http://blarg.co.uk/blog/javascript-date-formats

我的结果得出结论,以下格式在我测试的所有浏览器中都有效(示例使用日期“2013年8月9日”):

[完整年份]/[月份]/[日期编号]-月份可以是带或不带前导零的数字,也可以是短格式或长格式的月份名称,日期编号可以带或不带有前导零。

2013/08/092013/08/92013/8/092013/8/92013/08/092013年8月9日2013年8月09日2013年8月9日

【月份】/【全年】/【日期编号】-月份可以是带或不带前导零的数字,也可以是短格式或长格式的月份名称,日期编号可以带或不带有前导零。

08/2013/0908/2013/98/2013/098/2013/92013/09年8月2013年8月/9日2013年8月09日2013年8月/9日

用空格分隔的[整年]、[月名]和[日期编号]的任意组合-月名可以是短格式或长格式,日期编号可以是带或不带前导零。

2013年8月9日2013年8月09日2013年8月9日2013年8月9日2013年8月9日2013年8月9日等

也适用于“现代浏览器”(或除IE9及以下版本外的所有浏览器)

[全年]-[月号]-[日期号]-月号和日期号必须包含前导零(这是MySQL日期类型使用的格式)

2013-08-09

使用月份名称:有趣的是,在使用月份名称时,我发现只有月份名称的前3个字符被使用过,因此以下所有字符都是完全有效的:

new Date('9 August 2013');
new Date('9 Aug 2013');
new Date('9 Augu 2013');
new Date('9 Augustagfsdgsd 2013');

其他回答

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

所有浏览器

使用所使用的源格式格式化日期的最可靠方法是应用以下步骤:

使用new Date()创建Date对象使用.getDate()、.getMonth()和.getFullYear()分别获取日期、月份和年份根据目标格式将碎片粘贴在一起

例子:

var date='2015-11-09T10:46:15.097Z';函数格式(输入){var date=新日期(输入);返回[(“0”+date.getDate()).sslice(-2),(“0”+(date.getMonth()+1)).sslice(-2),date.getFullYear()].ejoin('/');}document.body.innerHTML=格式(日期);//产量:2015年9月11日

(另请参见此Fiddle)。


仅限现代浏览器

您还可以使用内置的.toLocaleDateString方法为您进行格式化。您只需要传递正确的区域设置和选项以匹配正确的格式,不幸的是,只有现代浏览器才支持这种格式(*):

var date='2015-11-09T10:46:15.097Z';函数格式(输入){返回新日期(输入).toLocaleDateString('en-GB'{年份:'数字',月份:'2-位',天:'2位数'});}document.body.innerHTML=格式(日期);//产量:2015年9月11日

(另请参见此Fiddle)。


(*)根据MDN,“现代浏览器”是指Chrome 24+、Firefox 29+、IE11、Edge12+、Opera 15+和Safari夜间版本

我们可以手动完成,非常简单。

var today=新日期();alert(“今天:”+今天);var dd=今天.getDate();警报(“dd:”+dd);var mm=today.getMonth()+1//一月是0!警报(“mm:”+mm);var yyyy=today.getFullYear();警报(“yyyy:”+yyyy);var hh=today.getHours();警报(“hh:”+hh);var min=today.getMinutes();警报(“min:”+min);var ss=today.getSeconds();警报(“ss:”+ss);如果(日<10){dd=“0”+dd} 如果(mm<10){毫米=‘0’+毫米} //今天=mm+'/'+dd+'/'+yyyy;//如果你想/改为-然后添加/今天=yyyy+“-”+mm+“-“+dd+”“+hh+”:“+mm+”:”+ss;今天=yyyy+“/”+mm+“/“+dd+”“+hh+”:“+mm+”:”+ss;//根据您的选择使用

懒惰的解决方案是使用带有正确区域代码的Date.toLocaleString

要获取可以运行的匹配区域列表

#!/bin/bash

[ -f bcp47.json ] || \
wget https://raw.githubusercontent.com/pculture/bcp47-json/master/bcp47.json

grep 'tag" : ' bcp47.json | cut -d'"' -f4 >codes.txt

js=$(cat <<'EOF'
const fs = require('fs');
const d = new Date(2020, 11, 12, 20, 00, 00);
fs.readFileSync('codes.txt', 'utf8')
.split('\n')
.forEach(code => {
  try {
    console.log(code+' '+d.toLocaleString(code))
  }
  catch (e) { console.log(code+' '+e.message) }
});
EOF
)

# print THE LIST of civilized countries
echo "$js" | node - | grep '2020-12-12 20:00:00'

这里是。。。。列表

af ce eo gv ha ku kw ky lt mg rw se sn sv xh zu 
ksh mgo sah wae AF KW KY LT MG RW SE SN SV

样品用途:

(new Date()).toLocaleString('af')

// -> '2020-12-21 11:50:15'

: )

(注意,这可能不是便携式的。)

我做了一个非常简单的格式化程序,它是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/