Convert String to date of specific timezone

2019-09-20 07:18发布

问题:

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