Home > Mobile >  How to fix inaccurate date format and time of moment.js in react native?
How to fix inaccurate date format and time of moment.js in react native?

Time:09-13

I have concern regarding date formatting and the time, happens right now I have record of 2022-09-12T21:18:38.000Z then after formatting that created_at the result is September 13 2022 05:18:38. The problem is the real data September 12 in formatted becomes September 13.

Package Moment Version:

"moment": "^2.29.4",
"moment-timezone": "^0.5.37",

Sample Code:

import moment from "moment";
import 'moment-timezone';

<Text fontSize="12" mt="2" fontWeight="300">{moment.tz(res?.created_at, "Asia/Manila").format("MMMM DD YYYY HH:mm:ss")}</Text>
<Text>{res?.created_at}</Text>

Current Output:

Current Output

CodePudding user response:

You have a time string with Z at the end, which is Zulu, or UTC 0. And you are using .moment.tz with "Asia/Manila". And "Asia/Manila" is UTC 8. And 2022-09-12T21:18:38.000Z in UTC 0 is September 13 2022 05:18:38 for UTC 8.

If you want to format this date to UTC time string - you can use any of those:

Using moment timezone:

moment.tz("2022-09-12T21:18:38.000Z", "UTC").format("MMMM DD YYYY HH:mm:ss")
=> 'September 12 2022 21:18:38'

Using plain moment

moment.utc("2022-09-12T21:18:38.000Z").format("MMMM DD YYYY HH:mm:ss")
=> 'September 12 2022 21:18:38'

So it will be for you:

{moment.tz(res?.created_at, "UTC").format("MMMM DD YYYY HH:mm:ss")}

or

{moment.utc(res?.created_at).format("MMMM DD YYYY HH:mm:ss")}
  • Related