簡體   English   中英

Android確定某個設備上的給定日期/時間是否低於DST

[英]Android determine if a given date/time is under DST on a device

根據設備中的當前用戶設置,是否可以確定給定的日期/時間是否會在夏令時下進行? 我不是在問這款手機目前是否有DST有效。 我需要知道使用手機中當前設置的給定(未來)日期是否屬於夏令時。 我可以使用Date(),Calendar()或Joda。 我也很好奇這個課程/方法如何處理歧義,例如本周日凌晨2:30(北美)。 那個時間不會存在,因為我們將超越它。 同樣地,在秋季,當我們退回時,凌晨1:30將發生兩次。 第一個凌晨1:30不在夏令時,但第二個是。

確定紀元時間是否在給定時區的DST中很容易。

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等),但READ javadoc非常謹慎地評論僅在未來時間使用它。 我也不會在將來使用它,因為地方當局不斷改變DST規則。 我在南澳大利亞(南半球+9:30 / + 10:30),紐約和豪勛爵島(半小時DST!+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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM