Home > Blockchain >  React render Epoch timestamp convert to am pm
React render Epoch timestamp convert to am pm

Time:01-03

I am doing a personal React.js project. I am fetching an API and one of the values it is an Epoch timestamp. I would like to render it as a human readable time like am/pm. The Epoch timestamp is render after a map. Below you can see the code:

{value.map((dog, c) => (
                  <div key={c}>
                    <div><b>Race name:</b> {dog.Venue}</div>
                    <div><b>Start time:</b> {dog.AdvertisedStartTime}</div>

{dog.AdvertisedStartTime} renders a number like: 1641079080000. This numbers are a time in the future, for instance 1:30pm

CodePudding user response:

You can do something like this. First define a helper function to convert Epoch to desired locale and use it inside the map. The function could be

function convertEpoch(value) {
  if (!value) {
    return ''
  }
  const time = new Date(value);
  if (isNaN(time.valueOf())) {
    return '';
  }
  return time.toLocaleString("en-US", { hour: "numeric", hour12: true });
}

And use it in your map like

{value.map((dog, c) => (
              <div key={c}>
                <div><b>Race name:</b> {dog.Venue}</div>
                <div><b>Start time:</b> {convertEpoch(dog.AdvertisedStartTime)}</div>

CodePudding user response:

let yourTimestamp = 1641079080000, (any number)
date = new Date(yourTimestamp * 1000),
dateVal = [
  date.getFullYear(),
  date.getMonth() 1,
  date.getDate(),
  date.getHours(),
  date.getMinutes(),
  date.getSeconds(),
];
console.log(dateVal);

Note that : Hours - mins and seconds depend on the time zone of your operating system. in different time zones it can be anything. Hence you can add the time zone offset to the time to create the GMT date:

let myDate = new Date();
date = new Date(timestamp*1000   myDate.getTimezoneOffset() * 60000)

CodePudding user response:

This is an example how we can get time very easy way.

let today= new Date().toLocaleTimeString(); console.log(today);

so you can try this one:

{value.map((dog, c) => (
          <div key={c}>
            <div><b>Race name:</b> {dog.Venue}</div>
            <div><b>Start time:</b> {convertEpoch(dog.AdvertisedStartTime.toLocaleTimeString();)}</div>

CodePudding user response:

This is an example how we can get time very easy way.

let today= new Date().toLocaleTimeString(); console.log(today); so you can try this one:

{value.map((dog, c) => (
          <div key={c}>
          {convertEpoch(dog.AdvertisedStartTime.toLocaleTimeString();)}</div>
  • Related