Convert String to date of specific timezone

谁都会走 提交于 2020-01-17 14:00:29

问题


I need to convert a string to date in a specific timezone.

Eg.

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

I need the final date in America/Chicago timezone. How can I achieve that?

I need to achieve a date in the desired timezone and not time in a desired timezone.

Time.now.in_time_zone("Eastern Time (US & Canada)") will give ActiveSupport::TimeWithZone format while I need the date format in desired timezone.


回答1:


Use DateTime:

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

Notice it is showing a time of 19:00. That's because a time is not specified so it thinks you are referring to 00:00 UTC, which is 19:00 CDT

One way to achieve what you are trying to do is:

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

This gives you a DateTime object at midnight on that date. You can then add time to get to a certain time of that day if you want.

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


来源:https://stackoverflow.com/questions/34175813/convert-string-to-date-of-specific-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!