You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将UTC时间转换为考虑夏令时的EST时间(含代码修改)

解决方案:将UTC时间转换为带夏令时的美国东部时间(EST/EDT)

Hey there! Let's tackle converting that UTC timestamp to Eastern Time (which automatically switches between EST and EDT for daylight saving time) in your Ruby code. Here are two solid approaches depending on your environment:

方案1: 使用ActiveSupport(Rails环境或独立使用)

If you're working in a Rails app, ActiveSupport is already included out of the box. For plain Ruby projects, you can install it via gem first.

修改后的代码:

# 如果你不是在Rails环境,先引入ActiveSupport
# require 'active_support/time'

# 获取原始UTC时间(确保它是Ruby Time对象)
utc_incident_time = nextOncall_result['incident']['created_at']

# 转换为美国东部时间(自动处理夏令时切换)
eastern_incident_time = utc_incident_time.in_time_zone('Eastern Time (US & Canada)')

# 拼接结果字符串
out_string += "Incident Created: #{eastern_incident_time}\n"

说明:

The in_time_zone method handles all the daylight saving time logic automatically — it'll show EDT during summer months and EST the rest of the year, without you having to hardcode offsets.

方案2: 纯Ruby方案(使用tzinfo gem)

If you prefer not to use ActiveSupport, the tzinfo gem is a great alternative that manages global timezone rules including DST.

步骤:

  1. Install the gem first:
gem install tzinfo
  1. Use this modified code:
require 'tzinfo'

# 获取美国东部时区实例(对应America/New_York,涵盖EST/EDT)
eastern_timezone = TZInfo::Timezone.get('America/New_York')

# 获取并转换UTC时间
utc_incident_time = nextOncall_result['incident']['created_at']
eastern_incident_time = eastern_timezone.utc_to_local(utc_incident_time)

# 更新输出字符串
out_string += "Incident Created: #{eastern_incident_time}\n"

重要注意事项

  • 确保时间是Ruby Time对象: If created_at comes as a string (like an ISO 8601 timestamp), parse it first to a Time object and enforce UTC:
    utc_time_str = nextOncall_result['incident']['created_at']
    utc_incident_time = Time.parse(utc_time_str).utc
    
  • Both methods will automatically adjust the time offset based on whether daylight saving time is in effect for the given timestamp.

内容的提问来源于stack exchange,提问作者Manju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:05:54