Android如何确定设备上的某个日期/时间是否处于夏令时状态

4
在设备中查看当前用户设置,是否有可能确定给定的日期/时间是否处于夏令时?我并不是在询问手机当前是否启用了夏令时。我需要知道一个(未来)日期,根据手机当前的设置,是否会进入夏令时。我可以使用Date()、Calendar()或Joda。同时,我也很想知道这个类/方法如何处理歧义,比如在北美洲这个星期日的上午2:30,那个时间将不存在,因为我们会跳过它。同样,在秋天,1:30 AM会发生两次,当我们倒回去时。第一个1:30 AM不在夏令时下,但第二个则在。

所以你只有本地日期/时间?那相对比较棘手。这是可行的,但我认为Joda Time或Date/Calendar都不容易实现。 (使用Noda Time会很容易;)) - Jon Skeet
嗯,有一些文件列出了所有的转换,通常预先计算到Unix纪元结束(请注意,这种情况是否实际发生还不确定,因为夏令时期定义偶尔会更改;最近俄罗斯停止使用夏令时并将所有时区向上移动了一个小时)。Android有这些文件。但我不知道是否可以在Java中访问它们。 - Jan Hudec
也许你可以使用 getDefault()?这将获取用户首选的时区。inDaylightTime(Date) 对你来说听起来很完美,但同一参考建议“大多数应用程序不应使用此方法。”我不理解为什么。 - kush
我认为我可以获取UTC时间。我正在计算日出/日落(http://www.codeagnostic.com/featured/calculate-sunrisesunset-java/),并传递基于getDefault()的时区,但这只会给出当前时区设置。如果日出/日落返回为日期对象,则可以从中获取.time,即UTC,对吗?但是,我该如何将其转换回本地时间?我刚刚看到了getOffset(int era,int year,int month,int day,int dayOfWeek,int timeOfDayMillis),以前不知道怎么错过了。我想知道它是否有效。而“int era”到底是什么? - MrGibbage
1个回答

2
确定给定时区的纪元时间是否处于夏令时很容易。
public static boolean isInDst(TimeZone tz, Date time)
{
    Calendar calendar = Calendar.getInstance(tz);
    calendar.setTime(time);
    // or supply a configured calendar with TZ as argument instead

    return calendar.get(Calendar.DST_OFFSET) != 0;
}

将本地时间转换为纪元时间在 API 方面看起来很容易

    Calendar calendar = Calendar.getInstance(tz);
    calendar.set(year, month, date, hourOfDay, minute);
    Date epoch = calendar.getTime();

由于含糊和间隙值,这变得棘手起来。

我编写了一个实用程序来测试模糊和间隙值,旨在仅使用Java API(不使用Joda-Time等)。但是请非常注意使用此程序仅适用于将来时间的javadoc注释。另外,我不建议将其用于远期时间,因为当地政府会不断更改夏令时规则。我在南澳大利亚(南半球+9:30 / +10:30),纽约和豪勋爵岛(半小时夏令时!+ 10:30 / + 11:00)上测试了此实用程序,但时间是个棘手的问题,所以请自行承担风险。

/**
 * Utility method to help handle Day Light Savings transitions. It
 * calculates possible time values the parameters could mean and returns all
 * possible values.
 * 
 * This method should ONLY be used for detecting ambiguous times in the
 * future, and not in the past. This method WILL fail to detect ambiguous
 * times in the past when the time zone would observe DST at the specified
 * time, but no longer does for current and future times. It also can fail
 * to detect ambiguous time in the past if at the specified time the DST
 * offset was different from the latest DST offset.
 * 
 * This method can fail to detect potentially ambiguous times if the
 * calendar uses leap seconds and leap second(s) are added/removed during
 * DST transition.
 * 
 * @param calendar
 *            the calendar to use, must have the correct time zone set. This
 *            calendar will be set, do not rely on the value set in the
 *            calendar after this method returns.
 * @param year
 * @param month
 * @param dayOfMonth
 *            zero based month index as used by {@link Calendar} object.
 * @param hourOfDay
 * @param minute
 * @return Array of {@link Date} objects with each element set to possible
 *         time the parameters could mean or null if the parameters are not
 *         possible, e.g. fall into the missing hour during DST transition,
 *         or complete garbage. One element array means there is only one
 *         non-ambiguous time the parameters can mean, that is, there is no
 *         DST transition at this time. Two element array means the
 *         parameters are ambiguous and could mean one of the two values. At
 *         this time more than two elements can not be returned, but
 *         calendars are strange things and this limit should not be relied
 *         upon.
 * @throws IllegalArgumentException
 *             if setting the specified values to the calendar throws same
 *             exception {@link Calendar#set(int, int, int, int, int)} or if
 *             invalid values are found but are not due to DST transition
 *             gap.
 */
public static Date[] getPossibleTimes(
        Calendar calendar,
        int year, int month, int dayOfMonth, int hourOfDay, int minute)
        throws IllegalArgumentException
{
    calendar.clear();
    try
    {
        // if calendar is set to non-lenient then setting time in the gap
        // due to DST transition will throw exception
        calendar.set(
                year,
                month,
                dayOfMonth,
                hourOfDay,
                minute
                );
    }
    catch (IllegalArgumentException ex)
    {
        if (calendar.isLenient())
        {
            throw ex;
        }
        return null;
    }

    // if validated fields do not match input values
    // this can be when set hour is missing due to DST transition
    // in which case calendar adjusts that hours and returns values
    // different to what was set
    if (
            calendar.get(Calendar.YEAR) != year
            || calendar.get(Calendar.MONTH) != month
            || calendar.get(Calendar.DAY_OF_MONTH) != dayOfMonth
            || calendar.get(Calendar.HOUR_OF_DAY) != hourOfDay
            || calendar.get(Calendar.MINUTE) != minute
            )
    {
        // the values are not possible.
        return null;
    }

    Date value1 = calendar.getTime();

    int dstSavings = calendar.getTimeZone().getDSTSavings();
    if (dstSavings == 0)
    {
        return new Date[] { value1 };
    }

    // subtract DST offset
    calendar.add(Calendar.MILLISECOND, - dstSavings);

    // check if the resulting time fields are same as initial times
    // this could happen due to DST transition, and makes the input time ambiguous
    if (
            calendar.get(Calendar.YEAR) == year
            && calendar.get(Calendar.MONTH) == month
            && calendar.get(Calendar.DAY_OF_MONTH) == dayOfMonth
            && calendar.get(Calendar.HOUR_OF_DAY) == hourOfDay
            && calendar.get(Calendar.MINUTE) == minute
            )
    {
        Date value2 = calendar.getTime();
        return new Date[] { value2, value1, };
    }

    // checking with added DST offset does not seem to be necessary,
    // but time zones are confusing things, checking anyway.

    // reset
    calendar.setTime(value1);

    // add DST offset
    calendar.add(Calendar.MILLISECOND, dstSavings);

    // same check for ambiguous time
    if (
            calendar.get(Calendar.YEAR) == year
            && calendar.get(Calendar.MONTH) == month
            && calendar.get(Calendar.DAY_OF_MONTH) == dayOfMonth
            && calendar.get(Calendar.HOUR_OF_DAY) == hourOfDay
            && calendar.get(Calendar.MINUTE) == minute
            )
    {
        Date value2 = calendar.getTime();
        return new Date[] { value1, value2, };
    }

    return new Date[] { value1, };
}

为了展示一些测试结果,这里是测试方法:

public static void test2()
{
    TimeZone tz = TimeZone.getTimeZone("America/New_York");

    System.out.format("id=%s\n", tz.getID());
    System.out.format("display=%s\n", tz.getDisplayName());
    System.out.format("raw offset=%f hours\n", tz.getRawOffset() / 1000f / 60f / 60f);
    System.out.format("dstSaving=%f minutes\n", tz.getDSTSavings() / 1000f / 60f);
    System.out.format("observesDST=%b\n", tz.observesDaylightTime());

    System.out.format("\n");

    // Time Tuple class simply holds local time, month is zero based as per Calendar
    TimeTuple [] testTimes = new TimeTuple[]{
            new TimeTuple(2014, 2, 9, 1, 59), // Non-ambiguous standard NY
            new TimeTuple(2014, 2, 9, 2, 00), // GAP NY
            new TimeTuple(2014, 2, 9, 2, 59), // GAP NY
            new TimeTuple(2014, 2, 9, 3, 00), // Non-ambiguous DST NY
            new TimeTuple(2014, 10, 2, 0, 59), // Non-ambiguous DST NY
            new TimeTuple(2014, 10, 2, 1, 00), // Ambiguous DST in NY
            new TimeTuple(2014, 10, 2, 1, 59), // Ambiguous DST in NY
            new TimeTuple(2014, 10, 2, 2, 00), // Non-ambiguous standard NY
    };

    Calendar calendar = GregorianCalendar.getInstance(tz);
    Date[] possibleTimeValues = null;
    for (TimeTuple tt: testTimes)
    {
        possibleTimeValues = getPossibleTimes(
                calendar,
                tt.year, // year
                tt.month, // zero based month
                tt.dayOfMonth, // date
                tt.hourOfDay, // hours
                tt.minute // minutes
                );
        printTimeAmbiguouity(calendar, possibleTimeValues, tt);
    }
}

static DateFormat TZ_FORMAT = new SimpleDateFormat("Z zzzz");

static DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S Z zzzz");

public static void printTimeAmbiguouity(Calendar calendar, Date[] possibleTimeValues, TimeTuple tt)
{
    TZ_FORMAT.setTimeZone(calendar.getTimeZone());
    DATE_FORMAT.setTimeZone(calendar.getTimeZone());

    System.out.format("\tinput local time   %s ----- ", tt.toString());

    if (possibleTimeValues == null)
    {
        System.out.format("Impossible/invalid/DST_gap\n");

        calendar.set(tt.year, tt.month, tt.dayOfMonth, tt.hourOfDay, tt.minute);
        Date adjustedTime = calendar.getTime();
        calendar.add(Calendar.HOUR, -6);
        Date limitTime = calendar.getTime();
        Date preTranstionTime = getPreviousTransition(calendar, adjustedTime, limitTime);
        Date postTranstionTime = new Date(preTranstionTime.getTime() + 1);

        System.out.format(
                "\tadjusted           %s\n\ttranstion   from   %s\n\t              to   %s\n",
                DATE_FORMAT.format(adjustedTime),
                DATE_FORMAT.format(preTranstionTime),
                DATE_FORMAT.format(postTranstionTime));
    }
    else if (possibleTimeValues.length == 1)
    {
        System.out.format("NonAmbiguous Valid\n");
        System.out.format("\ttimezone           %s\n", TZ_FORMAT.format(possibleTimeValues[0]));
    }
    else
    {
        System.out.format("Ambiguous\n");
        for (Date time: possibleTimeValues)
        {
            System.out.format("\tpossible value     %s\n", TZ_FORMAT.format(time));
        }
    }
    System.out.format("\n");
}

我不包括getPreviousTransition()方法,因为我认为该代码甚至更不适合生产环境。
测试输出:
id=America/New_York
display=Eastern Standard Time
raw offset=-5.000000 hours
dstSaving=60.000000 minutes
observesDST=true

input local time   2014-02-09 01:59 ----- NonAmbiguous Valid
timezone           -0500 Eastern Standard Time

input local time   2014-02-09 02:00 ----- Impossible/invalid/DST_gap
adjusted           2014-03-09 03:00:00.0 -0400 Eastern Daylight Time
transtion   from   2014-03-09 01:59:59.999 -0500 Eastern Standard Time
              to   2014-03-09 03:00:00.0 -0400 Eastern Daylight Time

input local time   2014-02-09 02:59 ----- Impossible/invalid/DST_gap
adjusted           2014-03-09 03:59:00.0 -0400 Eastern Daylight Time
transtion   from   2014-03-09 01:59:59.999 -0500 Eastern Standard Time
              to   2014-03-09 03:00:00.0 -0400 Eastern Daylight Time

input local time   2014-02-09 03:00 ----- NonAmbiguous Valid
timezone           -0400 Eastern Daylight Time

input local time   2014-10-02 00:59 ----- NonAmbiguous Valid
timezone           -0400 Eastern Daylight Time

input local time   2014-10-02 01:00 ----- Ambiguous
possible value     -0400 Eastern Daylight Time
possible value     -0500 Eastern Standard Time

input local time   2014-10-02 01:59 ----- Ambiguous
possible value     -0400 Eastern Daylight Time
possible value     -0500 Eastern Standard Time

input local time   2014-10-02 02:00 ----- NonAmbiguous Valid
timezone           -0500 Eastern Standard Time

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接