2

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?

Darkisa
  • 1,899
  • 3
  • 20
  • 40
  • Does this answer your question? [date-fns | How do I format to UTC](https://stackoverflow.com/questions/58561169/date-fns-how-do-i-format-to-utc) – iPhoenix Dec 15 '19 at 17:35
  • @iPhoenix Not really. That answers how to get a Date object into an ISO string and then perform calculations on the string. In my question my date/timestamp is already in an ISO string. What I am looking for is to use date-fns for easy formatting of that string. I can parse the ISO string also, but it just seems hackish if I am using date-fns. – Darkisa Dec 15 '19 at 17:42
  • Are you ok with using the vanilla javascript date object? – iPhoenix Dec 15 '19 at 17:44
  • I am. I am doing something similar now where I remove the timezone using vanilla JS and then using that string, I do my date operations, but I figured I try to see if there are better solutions. – Darkisa Dec 15 '19 at 17:46

2 Answers2

2

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.

Darkisa
  • 1,899
  • 3
  • 20
  • 40
0

Here is one solution that manually formats the string using the vanilla JS Date object:


const date = new Date('2019-12-15T20:00:00.000Z');

function format(date) {
  const hours = date.getUTCHours();
  const minutes = date.getMinutes();

  return (1 + ((hours - 1) % 12)) + ":" + minutes.toString().padStart(2, "0") + " " + ((hours > 11) ? "PM" : "AM");
}

format(date);
iPhoenix
  • 719
  • 7
  • 20