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


当前回答

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

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

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

其他回答

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

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

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');

您可以使用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"));

这是一个我经常使用的函数。结果为yyyy-mm-dd hh:mm:ss.nnn。

function date_and_time() {
    var date = new Date();
    //zero-pad a single zero if needed
    var zp = function (val){
        return (val <= 9 ? '0' + val : '' + val);
    }

    //zero-pad up to two zeroes if needed
    var zp2 = function(val){
        return val <= 99? (val <=9? '00' + val : '0' + val) : ('' + val ) ;
    }

    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    var h = date.getHours();
    var min = date.getMinutes();
    var s = date.getSeconds();
    var ms = date.getMilliseconds();
    return '' + y + '-' + zp(m) + '-' + zp(d) + ' ' + zp(h) + ':' + zp(min) + ':' + zp(s) + '.' + zp2(ms);
}

懒惰的解决方案是使用带有正确区域代码的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'

: )

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