如何将Date对象格式化为字符串?


当前回答

要获得“2010年8月10日”,请尝试:

var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})

有关浏览器支持,请参阅toLocaleDateString。

其他回答

在现代浏览器(*)中,您可以这样做:

var today = new Date().toLocaleDateString('en-GB', {
    day : 'numeric',
    month : 'short',
    year : 'numeric'
}).split(' ').join('-');

如果今天(1月24日)执行输出ᵗʰ, 2016):

'24-Jan-2016'

(*)根据MDN,“现代浏览器”是指Chrome 24+、Firefox 29+、Internet Explorer 11、Edge 12+、Opera 15+和Safari夜间版本。

已缩小2.39KB。一个文件。https://github.com/rhroyston/clock-js2010年8月10日为:

var str = clock.month
str.charAt(0).toUpperCase() + str.slice(1,3); //gets you "Aug"
console.log(clock.day + '-' + str + '-' + clock.year); //gets you 10-Aug-2010



不使用任何外部库的JavaScript解决方案:

var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)

试试看:

函数init(){var d=新日期();var day=d.getDate();var x=d.toDateString().substr(4,3);var year=d.getFullYear();document.querySelector(“#mydate”).innerHTML=day+'-'+x+'-'+年;}window.onload=init;<div id=“mydate”></div>

尽管new Date().toISOString().slice(0,10);对于我的正常用例来说,这是一个非常时髦的风格,我不喜欢前几个更为定制的字符串的答案,我给了自己几分钟的时间,让自己尽可能地时髦一点。

我没有看到我提出的解决方案,所以这里是。。。

((d,x)=>`${d.getFullYear()}-${x(d.getMonth()+1)}-${x(d.getDate())}`)
    (new Date(), (x)=>x.toString().padStart(2,"0"))

// today that produces
// '2022-09-28'
// the same as new Date().toISOString().slice(0, 10)
// but provides a good framework for other orders or values

伪IIFE获胜。

这里解决的问题当然是。。。

您可能需要使用前导零将天数和月份设置为小于10。因此,传入一个将强制转换为string&padStarts的函数。您需要在那里获得相同的日期,而不需要反复使用新的date()。获取“now”(newDate())并作为参数传入以供重用。你必须为getMonth添加1。这样做。

即使你需要映射到月份缩写之类的东西,你也可以使用类似的技巧,这并不是很可爱。

((d,x,y)=>`${x(d.getDate())} ${y(d.getMonth())} ${d.getFullYear()}`)
    (
     new Date(), 
     (x)=>x.toString().padStart(2,"0"), 
     (m)=>"jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec".split(',')[m]
    )

// As of this writing, that yields...
// '28 sep 2022'

(显然,为了增加清晰度,两者都去掉了空格;不希望代码块滚动)

…尽管我很难推荐这样做,但出于某种奇怪的原因,我只能从控制台创建测试值。真的很奇怪,没有toString('yyyy-mm-dd'),这是我所能做到的。