ES6格式化日期 [英] Format date in ES6

查看:2168
本文介绍了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格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆