ReactJS, How to convert unix Timestamp to/from Date example


This post talks about converting timestamp to/from date in reactjs/javascript.

In front end applications, Date manipulation is little bit different as client and server dates are different.

Some times, data contains date related information returned from backend API needs to format and convert to date. Reactjs applications offers two approaches

using momentjs library Intl DateTimeFormat

Timestamp is Unix style long value returning milli seconds elapsed from 1970/1/1 UTC

In javascript, Following are ways javascript is offering to get current timestamp.

You can check my previous post about Current timestamp in javascript

Date.now() 
new Date().getTime()
new Date().valueOff

Note, There are two timestamps, First local timestamp which is client side running on client timezone, Other is UTC timezone timestamp USA server’s Zone All the above lines of codes returns epoch Unix timestamp since 1971-01-01 time.

How to convert Unix timestamp to Date in reactjs

There are multiple ways , can convert epoch timestamp to date format in reactjs.

Intl.DateTimeFormat format method

In javascript, Intl.DateTimeFormat provides manipulation methods for date and timestamp related things.

DateTimeFormat accepts locale information as first parameter, second parameter is option It return an object of Intl.DateTimeFormat, calling format method will return the required date

Here is an example : Convert timestamp to date and time

let currentTimestamp = Date.now()
console.log(currentTimestamp); // get current timestamp
let date = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(currentTimestamp)

Locale is given as en-US, output desired date format is supplied in the second parameter as object.

Please note that all the output date converted to USA date and time format only

Output:

console.log(date);
1610380287270
01/11/2021, 9:21:27 PM

Here is an example : Convert timestamp to date only

let date = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(currentTimestamp) // 01/11/2021

example : Convert timestamp to time only

let date = new Intl.DateTimeFormat('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(currentTimestamp)//9:27:16 PM

Let’s see an example in react to convert array of timestamp into date

Complete example:

import React, { Component } from "react";
const empsApiData = [
    {
        id: '1',
        name: 'Franc',
        createdAt: 1610378858273

    },
    {
        id: '21',
        name: 'John',
        createdAt: 1610378858273


    },
    {
        id: '33',
        name: 'John',
        createdAt: 1610378858273

    },
    {
        id: '2',
        name: 'Krish',

    }
];
class ListComponent extends Component {


    constructor(props) {
        console.log('kiran ', empsApiData)
        super(props);
        const newEmps = empsApiData.map((emp) => ({
            "id": emp.id,
            "name": emp.name,
            "createdAt": new Intl.DateTimeFormat('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(emp.createdAt)
        }));
        this.state = {
            emps: newEmps
        }
    }



    render() {
        return (
            <div className="App">
                <ul>
                    {this.state.emps.map((item, index) => (
                        <li key={item.id}>
                            <span>{item.name}  </span>
                            <span>{item.createdAt}  </span>


                        </li>
                    ))}
                </ul>
            </div>
        );
    }
}


export default ListComponent;

Output seen in browser is

React convert timestamp to/from date

momentjs format ‘YYYY-MMM-DD’

First, install momentjs npm library as seen below

npm install momentjs --save

Next, import moment class into react component

import moment from 'moment'

In react component, pass the timestamp to moment object , call format method with parameter ‘L’, L means localized date formats

moment(emp.createdAt).format('L') returns 07/11/2011

There is another way you can use customize format

moment(emp.createdAt).format("YYYY-MMM-DD")

How to convert Date into timestamp in reactjs

Here date can be date object or string date, which is converted to Unix timestamp in milli seconds

getTime method

It is simple to convert timestamp from the given date.

First, You have to convert string to Date object using new Date(String) Next, call getTime() method on date object to return *Unix timestamp *

console.log((new Date("2021-01-01")).getTime()); // 1609459200000

Example: to convert current date to current timestamp

let date      = new Date();
var timestamp = date.getTime();

momentjs valueOf method

valueOf method return Unix seconds since epoch time.

Multiple with 1000 to get timestamp in mili seconds

moment("01/01/2021", "YYYY-MM-DD").valueOf() *1000

Conclusion

On this post, you will learned multiple ways to convert date to/from Unix timestamp in reactjs/JavaScript.

Hope it helps :-)

THE BEST NEWSLETTER ANYWHERE
Join 90,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts