如何将Date对象格式化为字符串?
当前回答
函数convert_month(i=0,option=“num”){//i=索引变量对象月=[{num:01,短:“Jan”,长:“Janer”},{num:02,短:“Feb”,长:“Februari”},{num:03,短:“Mar”,长:“March”},{num:04,短:“Apr”,长:“April”},{num:05,短:“May”,长:“May”},{num:06,短:“Jun”,长:“Juni”},{num:07,短:“Jul”,长:“July”},{num:08,短:“Aug”,长:“August”},{num:09,短:“Sep”,长:“Sept”},{num:10,短:“Oct”,长:“Octo”},{num:11,短:“Nov”,长:“十一月”},{num:12,短:“Dec”,长:“十二月”}];返回object_months[i][option];}var d=新日期();// https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascriptvar num=`${d.getDate()}-${convert_month(d.getMonth())}--${d.getFullYear()}';var short=`${d.getDate()}-${convert_month(d.getMonth(),“short”)}-${d.getFullYear()}`;var long=`${d.getDate()}-${convert_month(d.getMonth(),“long”)}-${d.getFullYear()}`;document.querySelector(“#num”).innerHTML=num;document.querySelector(“#short”).innerHTML=短;document.querySelector(“#long”).innerHTML=long;<p>数字:<span id=“num”></span>(默认值)</p><p>短:<span id=“Short”></span></p><p>长:<span id=“Long”></span></p>
其他回答
Date构造函数(和Date.parse())在构造日期时只接受一种格式作为参数,即ISO 8601:
// new Date('YYYY-MM-DDTHH:mm:ss.sssZ')
const date = new Date('2017-08-15')
但由于浏览器的差异和不一致性,强烈不建议从字符串中解析(MDN建议不要使用日期字符串创建日期)。
建议的替代方法是直接从数字数据构建Date实例,如下所示:
new Date(2017, 7, 15) // Month is zero-indexed
这就是解析。现在,要将日期格式化为所需的字符串,您有几个date对象的本地选项(尽管我认为没有一个符合您所需的格式):
date.toString() // 'Wed Jan 23 2019 17:23:42 GMT+0800 (Singapore Standard Time)'
date.toDateString() // 'Wed Jan 23 2019'
date.toLocaleString() // '23/01/2019, 17:23:42'
date.toGMTString() // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toUTCString() // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toISOString() // '2019-01-23T09:23:42.079Z'
对于其他格式选项,恐怕您必须使用Moment.js、day.js等库。
这篇文章中的日期格式提示归功于Zell Liew。
简单格式化程序:
function fmt(date, format = 'YYYY-MM-DDThh:mm:ss') {
const pad2 = (n) => n.toString().padStart(2, '0');
const map = {
YYYY: date.getFullYear(),
MM: pad2(date.getMonth() + 1),
DD: pad2(date.getDate()),
hh: pad2(date.getHours()),
mm: pad2(date.getMinutes()),
ss: pad2(date.getSeconds()),
};
return Object.entries(map).reduce((prev, entry) => prev.replace(...entry), format);
}
用法:
fmt(new Date(), 'YYYY-MM-DDThh:mm:ss'); // '2022-11-07T12:47:59'
对于任何想要复制、粘贴和采用真正简单的ES6解决方案的人来说:
const dateToString=d=>`${d.getFullYear()}-${('00'+(d.getMonth()+1)).slice(-2)}-${('0'+d.getDate()).spice(-2)}`//如何使用:const myDate=新日期(Date.parse('04 Dec 1995 00:12:00 GMT'))console.log(dateToString(myDate))//1995-12-04
尽管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'),这是我所能做到的。
new Date().toLocaleDateString()// "3/21/2018"
developer.mozilla.org上的更多文档
推荐文章
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- SQL Developer只返回日期,而不是时间。我怎么解决这个问题?
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA