Search code examples
javascriptreactjstypescriptdate-fns

how to create Date from data string in typescript (react) where string should be treated as GMT? (code attached)


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

Solution

  • Would you want is: new Date(parsedApiDate.setHours(parsedApiDate.getHours() + 10)) Where 10 is options. 10 here is your timezone.