convert Zulu time to +8GMT

Viewed 106

So I am using Mongodb to store datetime in an array.

2021-01-16T05:00:00.000Z I am wanting to convert that to +8GMT time in my reactJS app.

I am wondering if there is any easy way to do this?

I tried this

function Dateformat(props){
    var options = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Date(props.timestamp).toLocaleDateString([],options);
}

but I just get it prints the same time and date that is in the database

1 Answers

Edited answer

You can use the toLocaleString API under the Date Object.


const TimeDisplayComponent = (props) => {

  const convertedTime = new Date(props.theTimeYouwantToConvert).toLocaleString( 'sv', { timeZoneName: 'short' } );

  return <div>{convertedTime}</div>;
}

End of edited answer


The date you gave is an ISO-8601 format. To change it to GMT+8, you can do

const now = new Date();
const output = new Date(
  now.getTime() + (now.getTimezoneOffset() * 60_000)
);

Alternatively, you could always use a Date Time library like LuxonJS or DateFNS. It is often easier to handle time conversion with a library since there are too many problems associated with date-time manipulation in code (leap years, daylight savings, etc).

Related