简体   繁体   中英

In React how to convert UTC dateTime to more readable string inside the table

I have react component which showing records in the table. I have use 'useMemo' to define table structure and data. Some of its fields are date format which showing date like '2020-12-08T07:00:00Z'. I want to convert it to more friendly reading ie DD:MM:YYYY:Time?

Component

const EziSchedule = () =>{

const scheduleColumns = useMemo(
    () => [
      {
        Header: "Schedule Id",
        accessor: "eziScheduleId",
      },
      {
        Header: "Start Time",
        accessor: "startTime",   //need to convert??
      },
      {
        Header: "End Time",
        accessor: "endTime",    //need to convert??
      },
    ],
    []
  );

  return (
    <div>
    <h3>Schedule</h3>
    {props.searchCriteria&& props.searchCriteria.siteId!=0 &&

    <TableItem          
        apiUrl={api.EziTrackerSchedule}
        columns={scheduleColumns}
        itemType={EcpItemTypes.EziTracker}
        customParams= {props.searchCriteria}
        selectedRow={selectedScheduleRow}
    ></TableItems>}

Error

I have tried below code in useMemo:[... but it throw exception

       {
        Header: "Login DateTime",
        accessor: moment("loginDateTime","DD MM YYYY hh:mm:ss"),
      },

I can't comment, so...

Try this:

var d = new Date(YOUR DATE HERE);
var n = d.toLocaleString(CODE YOUR COUNTRY);

so, will be this way:

var d = new Date('2020-12-08T07:00:00Z');
var n = d.toLocaleString('pt-BR');

The result will be: 08/12/2020 04:00:00

Source (Here there are all the country codes): https://www.w3schools.com/jsref/jsref_tolocalestring.asp

If you want to output a variable with a string containing a date with momentjs you could go with moment(date).format(string). Please refer to the momentjs docs

moment().format();                                // "2014-09-08T08:02:17-05:00" (ISO 8601, no fractional seconds)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
moment().format("ddd, hA");                       // "Sun, 3PM"
moment().format("[Today is] dddd");               // "Today is Sunday"
moment('gibberish').format('YYYY MM DD');         // "Invalid date"

or with a variable

const date = "2021-01-05";
const formatted = moment(date).format(); 

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