Convert UTC to local time in Rails 3

后端 未结 6 949
面向向阳花
面向向阳花 2020-11-30 19:14

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

Say moment is some Time varia

6条回答
  •  长情又很酷
    2020-11-30 19:31

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

    > 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 conver to specific time zones rather than your own timezone, you're on the right track. However, instead of worrying about EST vs EDT, just pass in the general Eastern Time zone -- it will know based on the day whether it is 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 
    

提交回复
热议问题