Convert UTC to exact time using Rails 3

I'm having trouble converting UTC Time or TimeWithZone to local time in Rails 3.

Say moment - this is some Time variable in UTC format (for example, moment = Time.now.utc ). How to convert moment to my timezone taking care of DST (i.e. Using EST / EDT)?

More precisely, I would like to print “Monday, March 14th, 9am,” if the time is 9am EDT this morning, and “Monday is March 7th 9:00,” if it was 9am EST on the last Monday.

Hope there is another way?

Edit : At first I thought that “EDT” should be a recognized time zone, but “EDT” is not the actual time zone, more like a time zone state. For example, it would not make sense to ask Time.utc(2011,1,1).in_time_zone("EDT") . This is a bit confusing since "EST" is the actual time zone used in several places that do not use daylight saving time and are (UTC-5) for a year.

+83
timezone ruby ruby-on-rails ruby-on-rails-3 activesupport
Mar 14 2018-11-11T00:
source share
5 answers

Rails has its own names. See them with:

 rake time:zones:us 

You can also run rake time:zones:all for all time zones. To see more zone related tasks: rake -D time

So, to convert to EST, automatically maintain DST:

 Time.now.in_time_zone("Eastern Time (US & Canada)") 
+97
Mar 14 2018-11-11T00:
source share

Time#localtime will give you time in the current time zone of the machine on which the code is running:

 > moment = Time.now.utc => 2011-03-14 15:15:58 UTC > moment.localtime => 2011-03-14 08:15:58 -0700 

Update. If you want to switch to specific time zones, rather than your time zone, you are on the right track. However, instead of worrying about EST versus EDT, just go to the Eastern Time zone - he will know based on the bottom, whether EDT or EST:

 > Time.now.utc.in_time_zone("Eastern Time (US & Canada)") => Mon, 14 Mar 2011 11:21:05 EDT -04:00 > (Time.now.utc + 10.months).in_time_zone("Eastern Time (US & Canada)") => Sat, 14 Jan 2012 10:21:18 EST -05:00 
+102
Mar 14 2018-11-11T00:
source share

Actually there is a good Gem called local_time by basecamp to do all this only on the client side. I suppose:

https://github.com/basecamp/local_time

+14
Mar 19 '14 at 12:21
source share

It is easy to configure it using the local zone of your system. Just add this in your .rb application

 config.time_zone = Time.now.zone 

Then the rails should show you the local timestamps or you can use something like this instruction to get the local time

 Post.created_at.localtime 
+6
Oct 28 '16 at 0:03
source share

I don’t know why, but in my case it doesn’t work as suggested earlier. But it works as follows:

 Time.now.change(offset: "-3000") 

Of course you need to change the offset value to yours.

0
May 22 '16 at 4:27
source share



All Articles