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

: )

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

其他回答

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

使用此函数

toTimeString() and toLocaleDateString()

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

您引用的功能不是标准的Javascript,不太可能跨浏览器移植,因此不是很好的实践。ECMAScript 3规范将解析和输出格式功能留给Javascript实现。ECMAScript 5添加了ISO8601支持的子集。我相信你提到的toString()函数是一个浏览器的创新(Mozilla?)

有几个库提供了参数化这一点的例程,其中一些库提供了广泛的本地化支持。您还可以查看dojo.date.local中的方法。

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

//拉今年的最后两位数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));

d=日期.now();d=新日期(d);d=(d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+''+(d.getHours()>12?d.getHours()-12:d.getHoures())+':'+d.getMinutes()+''+(d.getHouers()>=12?“下午”:“上午”);console.log(d);