2

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

RussellHarrower
  • 6,470
  • 21
  • 102
  • 204

1 Answers1

0

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).

XingZhi Lim
  • 131
  • 2
  • 6
  • Sorry I kinda understand but where do I put the ``` props.timestamp ```` part because I get that now is the time now - and the output but don't you need to set the now to the props.timestamp for this to work? – RussellHarrower Dec 12 '20 at 07:38
  • Is your input a timestamp? Because that makes things so much easier as compared to ISO-8601 – XingZhi Lim Dec 12 '20 at 07:47
  • Mongodb stores it like 2021-01-16T05:00:00.000Z That is what I need to convert. – RussellHarrower Dec 12 '20 at 07:49
  • I just found an easier solution, you can use the [toLocaleString API](new Date(`2021-01-16T05:00:00.000Z`).toLocaleString( 'sv', { timeZoneName: 'short' } );), I've updated the solution – XingZhi Lim Dec 12 '20 at 07:53