Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Ruby DateTime from existing Time.zone for Rails?

I have users entering in dates in a Ruby on Rails website. I parse the dates into a DateTime object with something like:

date = DateTime.new(params[:year].to_i, params[:month].to_i, params[:day].to_i, params[:hour].to_i, params[:minute].to_i) 

or

date = DateTime.parse(params[:date]) 

Both DateTimes will not be in the time zone of the user which I previously set with something like:

Time.zone = "Pacific Time (US & Canada)" 

How do I parse the above DateTimes to be in the right time zone? I know the DateTime.new method has a 7th argument for the time offset. Is there an easy way to look up the offset for a time zone in a given time? Or should I be using something other than DateTime?

like image 275
at. Avatar asked Apr 06 '13 09:04

at.


People also ask

How do you create a DateTime object in Ruby?

A DateTime object is created with DateTime::new , DateTime::jd , DateTime::ordinal , DateTime::commercial , DateTime::parse , DateTime::strptime , DateTime::now , Time#to_datetime , etc. require 'date' DateTime. new(2001,2,3,4,5,6) #=> #<DateTime: 2001-02-03T04:05:06+00:00 ...>

How do you change timezone in Ruby?

You can do: Time. now + Time. zone_offset("PST") if you: require 'time' in your ruby script. guess, should have done that before commenting.

How do I change time zones in rails?

Configure your Rails app The most important one is the config. time_zone configuration in your config/application. rb file. ActiveRecord will help you convert from and to (which the documentation fails to explain) UTC and the time zone of your choice.

How do you parse time in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.


1 Answers

Try:

Time.zone = "Pacific Time (US & Canada)" Time.zone.parse('8-11-2013 23:59:59') #=> Fri, 08 Nov 2013 23:59:59 PST -08:00  

OR

Time.now.in_time_zone("Pacific Time (US & Canada)") 

OR

DateTime.now.in_time_zone("Pacific Time (US & Canada)") 
like image 195
shweta Avatar answered Sep 28 '22 05:09

shweta