将字符串转换为特定时区的日期

Convert String to date of specific timezone

我需要将字符串转换为特定时区的日期。

例如。

from = "June 13, 2015"

Date.strptime(from,"%b %d, %Y") #=> Sat, 13 Jun 2015

Date.strptime(from.strip,"%b %d, %Y").in_time_zone("America/Chicago") #=> Sat, 13 Jun 2015 00:00:00 CDT -05:00 which is ActiveSupport::TimeWithZone format

Date.strptime(from,"%b %d, %Y").in_time_zone("America/Chicago").to_date #=>Sat, 13 Jun 2015 which is in UTC Date class

我需要 America/Chicago 时区的最后日期。我怎样才能做到这一点?

我需要在所需时区中获取日期,而不是在所需时区中获取时间。

Time.now.in_time_zone("Eastern Time (US & Canada)") 将提供 ActiveSupport::TimeWithZone 格式,而我需要所需时区的日期格式。

使用日期时间:

from = "June 13, 2015"

DateTime.strptime(from,"%b %d, %Y").in_time_zone("America/Chicago")
=> Fri, 12 Jun 2015 19:00:00 CDT -05:00

注意它显示的时间是 19:00。那是因为没有指定时间所以它认为你指的是 00:00 UTC,即 19:00 CDT

实现您想要做的事情的一种方法是:

Date.strptime(from.strip,"%b %d, %Y").in_time_zone("America/Chicago").to_datetime
=> Sat, 13 Jun 2015 00:00:00 -0500

这会在该日期的午夜为您提供一个 DateTime 对象。然后,您可以根据需要添加时间以到达当天的特定时间。

my_date = Date.strptime(from.strip,"%b %d, %Y").in_time_zone("America/Chicago").to_datetime
  => Sat, 13 Jun 2015 00:00:00 -0500

my_date.in_time_zone("UTC")
  => Sat, 13 Jun 2015 05:00:00 UTC +00:00

my_date + 8.hours
  => Sat, 13 Jun 2015 08:00:00 -0500