Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: parse time to pull out hours and minutes using date-fns, ignroing timezones

My backend sends me a timestamp in the following format: 2019-12-15T20:00:00.000Z which is UTC time. Now all I need is to pull out the time without modifying it for timezones. I am using date-fns but every time I try to get the time I either get an Invalid Date or it modifies the time to the local timezone. Right now my code is:

import { format, parse, parseISO } from 'date-fns'

format(parseISO('2019-12-15T20:00:00.000Z'), 'h:mm a')

What I want is: 8:00 PM but what I get is 3:00 PM because its converting from UTC to EST time (my local timezone). I know I can do things like to IsoString and then parse the string, but I am looking for a way to use date-fns to do it so I don't have to write custom string parsers. There has to be an easy way to just ignore timezones?

like image 642
Darkisa Avatar asked Sep 13 '25 10:09

Darkisa


1 Answers

I am going to answer my own question with how I make it work in case it helps someone, but I am still looking to see if there is a better alternative of just using date-fns since mine seems a bit hackish:

What I do is remove the timezone from the ISO string and then use that time with date-fns:

let time = "2019-12-15T20:00:00.000Z".slice(0, -5)

The above is a time with no time zone, and because there is no timezone date-fns assumes the local timezone, so when you do:

format(parseISO(time), 'h:mm a')

you get: 8:00 PM, or whatever format you prefer. You just have to be careful with the string that you are slicing. If its always the same format then it should work.

like image 193
Darkisa Avatar answered Sep 14 '25 23:09

Darkisa