【问题标题】:Convert String to date of specific timezone将字符串转换为特定时区的日期
【发布时间】:2016-03-14 13:10:54
【问题描述】:

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

例如。

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

我需要美国/芝加哥时区的最终日期。我怎样才能做到这一点?

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

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

【问题讨论】:

  • 我猜您需要提供时间(而不是日期)才能转换为所需的时区。
  • 我会使用 DateTime。
  • 你的问题很模糊。日期实际上没有时区。 TIME 有一个时区。你想对日期做什么?
  • @Beartech 我需要根据所选管理时区中的所选日期过滤数据。

标签: ruby-on-rails ruby date ruby-on-rails-4 timezone


【解决方案1】:

使用日期时间:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2020-01-20
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多