1

I have an integer that represents a unix epoch time in millisecond precision and a time zone string. I need to create a TimeWithZone object with them.

epoch_ms_integer = 1586653140000

time_zone = "America/Los_Angeles"

Trying to convert to:

Sat, 11 Apr 2020 20:59:00 PDT -07:00

I was able to accomplish this by doing: Time.at(epoch_ms_integer/1000).asctime.in_time_zone("America/Los_Angeles") but was wondering if this is the best way to achieve this. The app I'm working on is configured to EST/EDT time zone so Time.at(epoch_ms_integer/1000) returns 2020-04-11 20:59:00 -0400.

I was able to find the asctime solution in one of the answers here Ruby / Rails - Change the timezone of a Time, without changing the value

the same question was asked here but no answer converting epoch time with milliseconds to datetime.

alisontague
  • 319
  • 1
  • 4
  • 14

1 Answers1

3

Assuming that the timestamp is in milliseconds, then 1586653140000 is

Epoch: 1586653140
  GMT: Sunday,   April 12, 2020 12:59:00 AM 
  PDT: Saturday, April 11, 2020 17:59:00 PM -in time zone America/Los Angeles

These are just 3 different ways to refer to a specific point in time around the world. Sat, 11 Apr 2020 20:59:00 PDT -07:00 and 2020-04-11 20:59:00 -0400 each refer to different points in time and not the same as epoch(1586653140)

Since the Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), it wouldn't make sense to take 1586653140 and only change the time zone without adding the zone's offset because now you are talking about another point in time.

To get the right "translation" from the epoch to any time zone you could just do

Time.zone = "GMT"
Time.zone.at(1586653140)
=> Sun, 12 Apr 2020 00:59:00 GMT +00:00
Time.zone = "America/Los_Angeles"
Time.zone.at(1586653140)
=> Sat, 11 Apr 2020 17:59:00 PDT -07:00

When working with dates in time zones in rails it is important to only use functions that take the set time zone into account:

DON’T USE

  • Time.now
  • Date.today
  • Date.today.to_time
  • Time.parse("2015-07-04 17:05:37")
  • Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z")

DO USE

  • Time.current
  • 2.hours.ago
  • Time.zone.today
  • Date.current
  • 1.day.from_now
  • Time.zone.parse("2015-07-04 17:05:37")
  • Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z").in_time_zone

Also keep in mind that in a Rails app, we have three different time zones:

  • system time,
  • application time, and
  • database time.

This post by thoughtbot explains things clearly.

robertoplancarte
  • 1,133
  • 11
  • 19