0

I have created a component using ReactJS where the information is received via json sent from the back-end.

    componentDidMount() {
    ObjectService.getObjects().then((response) => {
        this.setState({objects : response.data});
    });

I use componentDidMount for parsing the data.

I then render the component as

    render() {
    return (
        <div>
            {
                this.state.objects.map(
                    objects => 
                    <div className="objects">
                        <div className="object-wrapper">
                                <p>Owner: {objects.author}</p>
                                <p>Created: {objects.time_created}</p>
                                <p>Updated: {objects.time_updated}</p>
                        </div>
                    </div>
                )
            }
        </div>
    );

The above works fine but my issue is that objects.time_created shows time as 1617145200000. (I believe this is epoch time?!) How do I show this in human readable format? E.g. Tuesday, 30 March 2021 23:00:00

The solution was what @rafaat-dev mentioned below, I just used:

<p>Created: {new Date(objects.time_created).toUTCString()}</p>

Instead of:

<p>Created: {objects.time_created}</p>
Muhamad Gafar
  • 409
  • 3
  • 12

2 Answers2

1

you can try this:

const objects = {
    time_created: 1617145200000,
}

console.log('rawTime: ', objects.time_created); // rawTime: 1617145200000


const desiredTimeFormat = new Date(objects.time_created).toUTCString()

console.log(desiredTimeFormat) // Tue, 30 Mar 2021 23:00:00 GMT

there is a bunch of Instance methods inside the Date objects, you can read more about them here JavaScript Date objects

Raafat dev
  • 291
  • 1
  • 7
-1

Have you read the documentation on the in-built Date object?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#syntax

You just need to say something like:

function epochTime( t ) {
  return new Date(t);
}

If your epoch time is proper *nix epoch time (seconds since 1 January 1970 00:00:00 UTC) rather than the milliseconds epoch time Javascript expects, you might have to scale the value up by a factor 1000 before passing it to the Date constructor.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135