javascript 如何在 react.js 中转换时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48689876/
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-10-29 08:11:51  来源:igfitidea点击:

How to convert timestamp in react.js

javascriptreactjstimestamp

提问by Ghoyos

Im currently displaying a timestamp attached to each message sent in a message App Im building. However every stack overflow question I found on converting timestamps has to do with angular or native and I am trying to do this in react. Was wondering what code would I use to display something like (ex: 2/8/2018 11:04am || or something similar).

我当前显示附加到在消息 App Im 构建中发送的每条消息的时间戳。然而,我在转换时间戳时发现的每个堆栈溢出问题都与 angular 或 native 相关,我试图在 react 中做到这一点。想知道我将使用什么代码来显示类似的内容(例如:2/8/2018 11:04am || 或类似的内容)。

The current .push to the message array im using is:

当前使用的消息数组的 .push 是:

this.messagesRef.push(
    {
        content: this.state.userMsg,
        roomId: this.props.activeRoom.key,
        username: (this.props.user ? this.props.user.displayName : 'guest'),
        sentAt: this.props.firebase.database.ServerValue.TIMESTAMP
    }
);

My git hub push for this was (Git Link)

我的 git hub 推送是(Git Link)

回答by Rodius

Using Intl.DateTimeFormat

使用Intl.DateTimeFormat

If you have the timestamp number you can get it formatted as you asked like this:

如果您有时间戳编号,则可以按照您的要求对其进行格式化:

const timestamp = Date.now(); // This would be the timestamp you want to format

console.log(new Intl.DateTimeFormat('en-US', {year: 'numeric', month: '2-digit',day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'}).format(timestamp));

If you want the date with one number instead of two (2/8/2018 vs 02/08/2018) just change the format from '2-digit' to 'numeric' on the corresponding time unit.

如果您想要一个数字而不是两个数字(2/8/2018 vs 02/08/2018)的日期,只需将相应时间单位的格式从“2-digit”更改为“numeric”。