Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert timestamp in react.js

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).

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

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)

like image 833
Ghoyos Avatar asked Feb 08 '18 16:02

Ghoyos


People also ask

How do I convert timestamp to time in react?

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'}).

How do I convert time stamps to dates?

The constructor of the Date class receives a long value as an argument. Since the constructor of the Date class requires a long value, we need to convert the Timestamp object into a long value using the getTime() method of the TimeStamp class(present in SQL package).

How do I get only date from timestamp in react?

var day = date. getDate(); var month = date. getMonth(); var year = date. getFullYear();


2 Answers

Using 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.

like image 143
Rodius Avatar answered Oct 20 '22 04:10

Rodius


You can define method like this

const dateString = '2020-05-14T04:00:00Z'

const formatDate = (dateString) => {
  const options = { year: "numeric", month: "long", day: "numeric" }
  return new Date(dateString).toLocaleDateString(undefined, options)
}

console.log(formatDate(dateString))

if you want to read detail about this check this post https://css-tricks.com/how-to-convert-a-date-string-into-a-human-readable-format/

like image 43
Ankit Tiwari Avatar answered Oct 20 '22 04:10

Ankit Tiwari