ES6格式化日期

编程入门 行业动态 更新时间:2024-10-24 11:23:55
本文介绍了ES6格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在格式化一个日期,而不是momentjs或任何其他库,只是纯JS。而我想知道是否有办法简化这个与ES6

let currentDate = new Date(); const videosInformation = { time:currentDate.getHours()+':'+ currentDate.getMinutes(), date:(currentDate.getMonth()+ 1)+ '/'+ currentDate.getDate()+'/'+ currentDate.getFullYear(), gameId:Math.floor((Math.random()* 5000)+ 1)};

我看到在DOM中使用的东西就像 renderSomething = {`something :$ {someObj}`}

所以你不必做 renderSomething = {something: + {someObj}}

有什么我应该用来做这种格式吗?

解决方案

ES2015中没有添加任何类似 strftime no的内容。有一个ECMAScript国际化规范 ecma-402 ,启用本地化时间:

let date,time = new Date()。toLocaleString('en-US')。split(','); const videosInformation = {时间,日期, gameId:Math.floor((Math.random()* 5000)+ 1) };

哪些会给您美国本地化的 8/4/2015 和 5:29:19 PM 或者如果你真的想要24小时钟:

new Date()。 toLocaleString('en-US',{hour12:false})

然后你可以做一个子字符串时间,如果你想删除秒。

I am formatting a Date, with not momentjs or any other library, just pure JS. And I want to know if there is a way to simplify this with ES6

let currentDate = new Date(); const videosInformation = { time: currentDate.getHours() + ':' + currentDate.getMinutes(), date: (currentDate.getMonth() + 1) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear(), gameId: Math.floor((Math.random() * 5000) + 1) };

I saw that in the DOM you use something like renderSomething={`something: ${someObj}`}

so you don't have to do renderSomething={"something: " + {someObj}}

is there something I should use to do that kind of format?

解决方案

There's nothing in ES2015 that added something like strftime no. There's an ECMAScript internationalisation spec ecma-402 which enables localised time:

let date, time = new Date().toLocaleString('en-US').split(', '); const videosInformation = { time, date, gameId: Math.floor((Math.random() * 5000) + 1) };

Which would give you US localized 8/4/2015 and 5:29:19 PM Or if you really want a 24 hour clock:

new Date().toLocaleString('en-US', {hour12: false})

Then you can do a substring on the time if you want to strip out the seconds.

更多推荐

ES6格式化日期

本文发布于:2023-11-10 06:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574579.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!