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


当前回答

在我的情况下,我已将日期表“2022年7月1日”格式化为“2022-07-01”

常量格式日期=日期=>{const d=新日期(日期)let month=(d.getMonth()+1).toString()let day=d.getDate().toString()const year=d.getFullYear()如果(月长度<2){月=“0”+月}如果(日长度<2){天=“0”+天}return[年,月,日]。join('-')}console.log(格式日期('01/07/2022'))

其他回答

自定义格式设置函数:

对于固定格式,一个简单的函数即可完成任务。以下示例生成国际格式YYYY-MM-DD:

函数dateToYMD(日期){var d=date.getDate();var m=date.getMonth()+1//从0到11的月份var y=date.getFullYear();返回“”+y+“-”+(m<=9?“0”+m:m)+”-“+(d<=9!“0”+d:d);}console.log(dateToYMD(新日期(2017,10,5));//11月5日

OP格式可以如下生成:

函数dateToYMD(日期){var strArray=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];var d=date.getDate();var m=strArray[date.getMonth()];var y=date.getFullYear();返回“”+(d<=9?“0”+d:d)+“-”+“+m+”-“+y;}console.log(dateToYMD(新日期(2017,10,5));//11月5日

注意:然而,扩展JavaScript标准库通常不是一个好主意(例如,通过将此函数添加到Date的原型中)。

更高级的功能可以基于格式参数生成可配置的输出。

如果编写一个格式化函数太长,那么周围有很多库可以执行它。其他一些答案已经列举了它们。但日益增加的依赖性也有反作用。

标准ECMAScript格式化函数:

自从ECMAScript的最新版本以来,Date类具有一些特定的格式化函数:

toDateString:依赖于实现,仅显示日期。https://262.ecma-international.org/#sec-日期.协议类型.日期new Date().toDateString();//例如“2016年11月11日星期五”


toISOString:显示ISO 8601日期和时间。https://262.ecma-international.org/#sec-日期.协议类型.toisostringnew Date().toISOString();//例如“2016-11-21T08:00:00.000Z”


toJSON:JSON的Stringer。https://262.ecma-international.org/#sec-日期.原型.项目new Date().toJSON();//例如“2016-11-21T08:00:00.000Z”


toLocaleDateString:依赖于实现,区域设置格式的日期。https://262.ecma-international.org/#sec-日期.协议类型.颜色日期字符串new Date().toLocaleDateString();//例如“2016年11月21日”


toLocaleString:依赖于实现,是区域设置格式的日期和时间。https://262.ecma-international.org/#sec-日期.协议类型.颜色字符串new Date().toLocaleString();//例如“2016年11月21日上午08:00:00”


toLocaleTimeString:依赖于实现,以区域设置格式表示时间。https://262.ecma-international.org/#sec-日期.协议类型.颜色时间字符串new Date().toLocaleTimeString();//例如“08:00:00 AM”


toString:日期的通用toString。https://262.ecma-international.org/#sec-日期.协议类型.测试new Date().toString();//例如“2016年11月21日星期五08:00:00 GMT+0100(西欧标准时间)”

注意:可以使用这些格式生成自定义输出>

new Date().toISOString().slice(0,10)//返回YYYY-MM-DD

示例片段:console.log(“1)”+new Date().toDateString());console.log(“2)”+new Date().toISOString());console.log(“3)”+new Date().toJSON());console.log(“4)”+new Date().toLocaleDateString());console.log(“5)”+new Date().toLocaleString());console.log(“6)”+new Date().toLocaleTimeString());console.log(“7)”+new Date().toString());console.log(“8)”+new Date().toISOString().slice(0,10));

指定标准函数的区域设置:

上面列出的一些标准函数取决于语言环境:

到LocaleDateString()到LocaleTimeString()到LocalString()

这是因为不同的文化使用不同的格式,并以不同的方式表达他们的日期或时间。默认情况下,该函数将返回在其运行的设备上配置的格式,但这可以通过设置参数(ECMA-402)来指定。

toLocaleDateString([locales[, options]])
toLocaleTimeString([locales[, options]])
toLocaleString([locales[, options]])
//e.g. toLocaleDateString('ko-KR');

选项第二个参数允许在所选区域设置中配置更具体的格式。例如,月份可以显示为全文或删节。

toLocaleString('en-GB', { month: 'short' })
toLocaleString('en-GB', { month: 'long' })

示例片段:console.log(“1)”+new Date().toLocaleString('en-US'));console.log(“2)”+new Date().toLocaleString('ko-KR'));console.log(“3)”+新日期().toLocaleString('de-CH'));console.log(“4)”+new Date().toLocaleString('en-GB',{hour12:false}));console.log(“5)”+new Date().toLocaleString('en-GB',{hour12:true}));

关于区域设置的一些良好做法:

大多数人不喜欢他们的日期以外国人的格式显示,因此,尽可能保持默认的语言环境(而不是到处设置“en-US”)。实现从UTC到UTC的转换可能具有挑战性(考虑到DST、时区不是1小时的倍数等)。尽可能使用经过良好测试的库。不要假设语言环境与一个国家相关:几个国家都有很多语言环境(加拿大、印度等)避免通过非标准方式检测区域设置。在这里,您可以了解到多个陷阱:检测键盘布局、按地理位置检测区域设置等。。

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

文档中的示例:

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

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

一行中请求的格式-没有库和Date方法,只有正则表达式:

var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')

在我的测试中,这在主要浏览器(Chrome、Safari、Firefox和IE)中可靠地工作。正如@RobG所指出的,Date.protype.toString()的输出依赖于实现,因此对于国际或非浏览器实现,只需测试输出,以确保它在JavaScript引擎中正常工作。您甚至可以添加一些代码来测试字符串输出,并在执行正则表达式替换之前确保其与预期匹配。

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

它在InternetExplorer11、Firefox和Chrome中的工作方式相同(当选择en-UK时,Chrome80.x显示12小时格式)。

const d=新日期('2010/08/05 23:45')//26.3.2020const dtfUK=新Intl.DateTimeFormat('UK',{年:'数字',月:'2位数',日:'2位',小时:'2-位数',分钟:'2-位',秒:'2-数位'})//const dtfUS=新Intl.DateTimeFormat('en',{年:'数字',月:'2位数',日:'2位',小时:'2-位数',分钟:'2-位',秒:'2-数位'})//console.log(dtfUS.format(d));//2010年5月8日下午11:45:00console.log(dtfUK.format(d));//05.08.2010 23:45:00/*node.js:2010年5月8日,晚上11:45:002010-08-05 23:45:00*/

有什么更一般的吗?

var d=新日期('2010-08-10T10:34:56.789Z');var str=d.toDateString()+/-2010年8月10日星期二“”+d.toTimeString().split(“”)[0]+/-12:34:56,GMT+0x0(GMT+00:00)“”+(d.getMonth()+101)+/-108“”+d.获取毫秒();//789console.log(str);//2010年8月10日星期二12:34:56 108 789console.log(//$1周二$2 8月$3 11$4 2020$5 12$6 34$7 56$8 108$9 789str.replace(/(\S{3})(\S}3)(\d{1,2})); // 2010年8月10日12:34.789(星期二)/*$1:星期二工作日字符串$2:8月短文本$3:11天$4:2010年$5:12小时$6:34分钟$7:56秒$8:08个月$9:789毫秒*/

或例如1行IIFE“库”;-)

控制台日志((函数(frm,d){return[d.toDateString(),d.toTimeString().split(“”)[0],(d.getMonth()+101),d.getMilliseconds()].jjoin(“).replace(/(\S{3})(\S})('$4/$8/$3$5:$6($1)',新日期()));

如果不需要,可以删除无用的部件和/或更改索引。