【问题标题】:Obtaining a Time Zone Locale that is Different from Local Machine [closed]获取与本地计算机不同的时区区域设置 [关闭]
【发布时间】:2015-03-25 17:21:28
【问题描述】:

我正在编写一个返回时区的方法,即具有不同日期的 UTC 时区。此方法应采用用户设置的时区作为输入。我知道我必须越过国际日期变更线才能到达不同日期的时区,但我不确定我是否在这里遗漏了什么。 例如如果我在 EST 时区,则返回日期与 EST 时区不同的时区。

public String getDifferentDate (String timeZone) {
    //Calculate the time zone offset required to cross International Date line
    //RETURN newTimeZone with different date.
}

【问题讨论】:

  • 也许你应该添加一些代码向我们展示你所做的尝试并解释更多你真正想要的东西。
  • 哪种语言? Java 还是 Python?
  • 语言无关紧要。 Java 或 Python 都可以使用
  • 有多个时区的日期不同。应该退回哪一个?
  • 任何!这里的目的是获取不同日期的时区!如果有多个时区,则返回日期更改最先出现的那个。

标签: java python date datetime timezone


【解决方案1】:

获取某个时区的日期与给定时区中的当前日期不同:

#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz

def get_timezone_with_different_date(input_timezone_id, now=None):
    """
    input_timezone_id: the tz database id such as 'America/New_York'
    now: a naive datetime object representing time in input_timezone_id
    """
    input_tz = pytz.timezone(input_timezone_id)
    if now is None:
       now = datetime.now(input_tz) # use the current time
    else: 
       now = input_tz.localize(now, is_dst=None) # make it timezone-aware

    for tz in map(pytz.timezone, pytz.all_timezones_set):
        if tz.normalize(now.astimezone(tz)).date() != now.date():
             return tz.zone
    assert 0, 'never happens'

例子:

>>> get_timezone_with_different_date('US/Eastern')
'Australia/Melbourne'

注意:一般情况下,您无需跨越国际日期变更线即可获得不同的日期。

【讨论】:

  • 非常感谢您的时间 J.F. Sebastian。我们如何在 Java 中做到这一点?
  • @user3001378:您可以使用Joda Time 或Java 中的类似库来实现相同的算法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-04
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-17
相关资源
最近更新 更多