Javascript ES6 格式化日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31792398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:12:13  来源:igfitidea点击:

Format date in ES6

javascriptdateecmascript-6

提问by Non

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

我正在格式化一个日期,没有 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)
};

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

我看到在 DOM 中你使用了类似的东西 renderSomething={`something: ${someObj}`}

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

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

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

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

回答by Kit Sunde

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

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

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/2015and 5:29:19 PMOr if you really want a 24 hour clock:

这会给你美国本地化8/4/20155:29:19 PM或者如果你真的想要一个 24 小时制:

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

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

如果你想去掉秒,你可以在时间上做一个子字符串。

You can read more about date and time at MDT docs.

您可以在MDT 文档中阅读有关日期和时间的更多信息。