sl_bug
sl_bug

Reputation: 5336

Convert date to time in some zone on rails 3.2

I have 3 objects - @date, @time and @datetime. How to convert object @date to time (and to datetime) using zones from objects @time and @datetime?

Example:

@date = '2012-1-1'
@time = '2012-08-14 14:48:47 +1000'
@datetime = '2012-08-14 14:48:47 +0500'
@converted_date_to_time = ...     # should give '2012-1-1 00:00:00 +1000'
@converted_date_to_datetime = ... # should give '2012-1-1 00:00:00 +0500'

Upvotes: 1

Views: 1538

Answers (2)

Dan Caddigan
Dan Caddigan

Reputation: 1598

If you want the time parsed in the zone specified in config.time_zone, you can use:

Time.zone.parse('2012-08-14 14:48:47 +1000')

I wouldn't use DateTime, though, unless you have some special requirements as the Time class now supports a huge range of dates and Rails handles time zones through Time.zone really well.

Upvotes: 2

toxaq
toxaq

Reputation: 6838

You can parse a date like this

1.9.3p194> date = '2012-1-1'
=> "2012-1-1" 
1.9.3p194> Time.parse(date)
=> 2012-01-01 00:00:00 +1300 

That is using my local timezone (Wellington, +13). You can also parse your time strings the same way

1.9.3p194> time = '2012-08-14 14:48:47 +1000'
=> "2012-08-14 14:48:47 +1000" 
1.9.3p194> Time.parse(time)
=> 2012-08-14 16:48:47 +1200 

You will notice it looks a little wrong but that's because it is using my local timezone again, so it is accurate but currently in my timezone. You can then convert it to what ever timezone you want.

1.9.3p194> Time.parse(time).in_time_zone('Moscow')
=> Tue, 14 Aug 2012 08:48:47 MSK +04:00

1.9.3p194> Time.parse(time).in_time_zone('Brisbane')
=> Tue, 14 Aug 2012 14:48:47 EST +10:00 

This will work the same for your datetime string as well.

If you want to use a specific timezone, you can do that as follows

1.9.3p194> Time.find_zone('Tokyo').parse('2012-08-14 14:48:47 +0500')
=> Tue, 14 Aug 2012 18:48:47 JST +09:00 

Upvotes: 3

Related Questions