将 Date 对象转换为 TimeWithZone [英] converting Date object to TimeWithZone

查看:62
本文介绍了将 Date 对象转换为 TimeWithZone的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 Date 对象转换为 TimeWithZone 对象,表示给定时区中那一天的开始.

I need to convert a Date object into a TimeWithZone object representing the beginning of that day in a given time zone.

以下方法有效,但似乎过于复杂,因为它需要我将日期转换为字符串:

The following approach works, but seems too convoluted as it requires me to convert the date to a string:

?> date = Date.parse("2010-02-17")
=> Wed, 17 Feb 2010
>> ActiveSupport::TimeZone['Eastern Time (US & Canada)'].parse(date.to_s)
=> Wed, 17 Feb 2010 00:00:00 EST -05:00
>> ActiveSupport::TimeZone['UTC'].parse(date.to_s)
=> Wed, 17 Feb 2010 00:00:00 UTC 00:00

我想念有没有更好的方法?

Is there a better way I'm missing?

人们建议以下变体:

?> date.to_datetime.in_time_zone('Eastern Time (US & Canada)').beginning_of_day
=> Tue, 16 Feb 2010 00:00:00 EST -05:00

如您所见,这不是等效的转换,因为它在美国东部时间 2 月 16 日开始时离开我,而不是美国东部时间 2 月 17 日开始时.

As you can see, this isn't an equivalent conversion since it leaves me at the start of Feb. 16th EST, instead of the start of Feb. 17th EST.

推荐答案

我迟到了,但这仍然是一个很好的问题.ActiveSupport 的 in_time_zone 从 O.P. 开始就被引入了,但它完全符合你的要求,无需解析字符串(慢)或设置 Time.zone(有风险):

I'm late to the party, but this is still a great question. ActiveSupport's in_time_zone was introduced since the O.P., but it does exactly what you want without parsing a string (slow) or setting Time.zone (risky):

>> date = Date.parse("2010-02-17")
=> Wed, 17 Feb 2010
>> date.in_time_zone('Eastern Time (US & Canada)')
=> Wed, 17 Feb 2010 00:00:00 EST -05:00

当然,如果您想以 UTC 表示一天的开始,您可以这样做:

Of course if you want the beginning of day expressed at utc, you can do this:

>> date.in_time_zone('Eastern Time (US & Canada)').utc
=> 2010-02-17 05:00:00 UTC

这篇关于将 Date 对象转换为 TimeWithZone的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆