ES6格式化日期 [英] Format date in 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格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!