Your destination for complete Tech news

How to convert a Unix timestamp to time in React JS?

2.65K 0
< 1 min read

In ReactJS, you can convert a Unix timestamp to a human-readable time using the built-in Date object. Here’s how you can do it:

import React from 'react';

class UnixTimestampConverter extends React.Component {
  render() {
    const unixTimestamp = 1629025333; // Replace this with your Unix timestamp

    const date = new Date(unixTimestamp * 1000); // Convert Unix timestamp to milliseconds

    // Get the various components of the date
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // Month is 0-indexed, so we add 1
    const day = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();

    return (
        <p>Unix Timestamp: {unixTimestamp}</p>
        <p>Converted Time: {`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`}</p>

export default UnixTimestampConverter;

In this example, replace the unixTimestamp variable with your actual Unix timestamp. The Date object in JavaScript works with Unix timestamps in milliseconds, so you need to multiply the timestamp by 1000 to convert it to milliseconds.

The getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), and getSeconds() methods of the Date object allow you to extract individual components of the timestamp and then you can format them as needed.

Remember that the local time of the user’s device will be used by the Date object. If you need to display the time in a specific timezone, you might need to use external libraries like moment-timezone or handle the timezone offset manually.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.