1

Question

By default, the Chronic gem uses the system timezone as the default timezone.

They mention here (https://github.com/mojombo/chronic#time-zones), that I can use ActiveSupports Time.zone to change this. But i'm not using Rails, i'm using Sinatra and including active support just to utilize the timezone class seems unnecessary.

How else can I do this?

What i'm trying to do.

I'm using Chronic for system reporting / dashboards and stats.

The servers are storing timestamps in the created_at fields in the DB at utc time. But of course we run our reports as PDT.

I want to set the default timezone to America/Los_Angeles. So that:

d = Chronic.parse("1 days ago at midnight")  
date = d.localtime   #Should give me a date like "2013-05-27 00:00:00"
utc_date = date.utc  #Should give me a date like "2013-05-27 07:00:00"

How can I accomplish this?

Community
  • 1
  • 1
Mark Evans
  • 810
  • 10
  • 18

1 Answers1

2

I'd post this as a comment as I'm uncomfortable taking any credit for what is basically someone else's answer but I wouldn't have enough room in the comments. The TZ environment variable is helpful in these situations. Take a look at this:

def with_time_zone(tz_name)
  prev_tz = ENV['TZ']
  ENV['TZ'] = tz_name
  yield
ensure
  ENV['TZ'] = prev_tz
end

with_time_zone('US/Pacific') { Chronic.parse("1 days ago at midnight") }
# => 2013-05-27 08:00:00 0100
with_time_zone('US/Pacific') { Chronic.parse("1 days ago at midnight").localtime }
# => 2013-05-27 00:00:00 -0700

You can either set the server's localtime with the correct zone, get the whole app to run with the TZ var set how you like, or manipulate the time on the way out.

Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
ian
  • 12,003
  • 9
  • 51
  • 107