如何将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'),这是我所能做到的。
推荐文章
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有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