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


当前回答

如果你想要一个简短的、人类可读的函数,这个函数很容易调整以适合你。

timeStamp参数是1970年的毫秒-它由new Date().getTime()和许多其他设备返回。。。

好吧,我改变主意了。我包含了一个额外的零填充函数。诅咒!

 function zeroPad(aNumber) {
     return ("0"+aNumber).slice(-2);
 }
 function humanTime(timeStamp) {
    var M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var D = new Date(timeStamp); // 23 Aug 2016 16:45:59 <-- Desired format.
    return D.getDate() + " " + M[D.getMonth()] + " " + D.getFullYear() + " " + D.getHours() + ":" + zeroPad(d.getMinutes()) + ":" + zeroPad(D.getSeconds());
 }

其他回答

已缩小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



要获得“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。

new Date().toLocaleDateString()// "3/21/2018"

developer.mozilla.org上的更多文档

Sugar.js对Date对象有很好的扩展,包括Date.format方法。

文档中的示例:

Date.create().format('{Weekday} {Month} {dd}, {yyyy}');

Date.create().format('{12hr}:{mm}{tt}')

尽管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'),这是我所能做到的。