Home > database >  how to create Date from data string in typescript (react) where string should be treated as GMT? (co
how to create Date from data string in typescript (react) where string should be treated as GMT? (co

Time:07-25

In React/Typescript how can I create a Date from a datetime string (received from a REST API), where the assumption is that it is UTC time.

String in question is: "2022-01-31T14:00:00". So it doesn't have the "Z" at the end which seems to be created when I try creating it manually. It's a datetime string I am receiving from a REST API so I'm a bit stuck with this.

So in the console out you see I am getting:

2022-01-31T14:00:00 => Monday, January 31st, 2022 at 2:00:00 PM GMT 10:00

But I really what to get the following (assuming I'm running this in the 10H timezone):

2022-01-31T14:00:00 => Tuesday, March 1st, 2022 at 12:00:00 AM GMT 10:00

Code

import { format } from "date-fns";

const tsCreatedDate = new Date(2022, 2, 1)
console.log("Starting Date: ", format(tsCreatedDate, 'PPPPpppp'))

const tsCreatedDateStr = tsCreatedDate.toISOString()
const dateStrFromApi: string = "2022-01-31T14:00:00"

const parsedApiDate = new Date(dateStrFromApi)
const parsedTsDate = new Date(tsCreatedDateStr)

console.log("Typescript Direct: ", tsCreatedDateStr, " => ", format(parsedTsDate , 'PPPPpppp'))
console.log("WEB API Date Str : ", dateStrFromApi  , " => ", format(parsedApiDate, 'PPPPpppp'))

Console:

Starting Date:  Tuesday, March 1st, 2022 at 12:00:00 AM GMT 10:00
src/App.tsx:12
Typescript Direct:  2022-02-28T14:00:00.000Z  =>  Tuesday, March 1st, 2022 at 12:00:00 AM GMT 10:00
src/App.tsx:20
WEB API Date Str :  2022-01-31T14:00:00  =>  Monday, January 31st, 2022 at 2:00:00 PM GMT 10:00

CodePudding user response:

I recommend using moment js.

moment(new Date(dateStrFromApi).getTime()).utc().format()

Albert

CodePudding user response:

Using new Date(Date.UTC(year, month, day, hour, minute, second)) you can create a Date-object from a specific UTC time.

  • Related