Crashalot
Crashalot

Reputation: 34513

Get date value in Pacific Standard Time for Ruby?

We would like today's date in Pacific Standard Time in Ruby using the Date class (because we use Mongo and Mongo can't handle the Time class). How can we do this?

Essentially, we want to guarantee that today = Date.to_mongo Date.today always returns today's date in PST.

We're on Rails 3.12 and using MongoMapper.

Thanks.

Upvotes: 0

Views: 197

Answers (1)

Neil Slater
Neil Slater

Reputation: 27207

This is a little low-level (in that you manipulate the offset, rather than declare 'PST' somewhere), but might do the trick:

d = DateTime.now.new_offset('-08:00').to_date

Not sure if you have daylight-saving time, which would make things more complicated?

You could put this snippet into Date.today, but that would over-ride machine settings, so I'd recommend something more specific like

class Date
  def self.today_pst
    DateTime.now.new_offset('-08:00').to_date
  end
end

today = Date.to_mongo Date.today_pst

Also, warning, if you convert back to Time or DateTime, the zone is not preserved.

Upvotes: 2

Related Questions