简体   繁体   中英

React render Epoch timestamp convert to am pm

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

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)

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>

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM