Java Code Examples for android.icu.util.TimeZone#getTimeZone()

The following examples show how to use android.icu.util.TimeZone#getTimeZone() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DateFormatRegressionTestJ.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void run() {
    SimpleDateFormat sdf = (SimpleDateFormat) sdf_.clone();
    TimeZone defaultTZ = TimeZone.getDefault();
    TimeZone PST = TimeZone.getTimeZone("PST");
    int defaultOffset = defaultTZ.getRawOffset();
    int PSTOffset = PST.getRawOffset();
    int offset = defaultOffset - PSTOffset;
    long ms = UTC_LONG - offset;
    try {
        int i = 0;
        while (i < 10000) {
            Date date = sdf.parse(TIME_STRING);
            long t = date.getTime();
            i++;
            if (t != ms) {
                throw new ParseException("Parse Error: " + i + " (" + sdf.format(date) 
                          + ") " + t + " != " + ms, 0);
            }
        }
    } catch (Exception e) {
        errln("parse error: " + e.getMessage());
    }
}
 
Example 2
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestPRTOffset()
{
    TimeZone tz = TimeZone.getTimeZone( "PRT" );
    if( tz == null ) {
        errln( "FAIL: TimeZone(PRT) is null" );
    }
    else{
        if (tz.getRawOffset() != (-4*millisPerHour))
            warnln("FAIL: Offset for PRT should be -4, got " +
                  tz.getRawOffset() / (double)millisPerHour);
    }

}
 
Example 3
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestDisplayName2() {
    Date now = new Date();

    String[] timezones = {"America/Chicago", "Europe/Moscow", "Europe/Rome", "Asia/Shanghai", "WET" };
    String[] locales = {"en", "fr", "de", "ja", "zh_TW", "zh_Hans" };
    for (int j = 0; j < locales.length; ++j) {
        ULocale locale = new ULocale(locales[j]);
        for (int i = 0; i < timezones.length; ++i) {
            TimeZone tz = TimeZone.getTimeZone(timezones[i]);
            String displayName0 = tz.getDisplayName(locale);
            SimpleDateFormat dt = new SimpleDateFormat("vvvv", locale);
            dt.setTimeZone(tz);
            String displayName1 = dt.format(now);  // date value _does_ matter if we fallback to GMT
            logln(locale.getDisplayName() + ", " + tz.getID() + ": " + displayName0);
            if (!displayName1.equals(displayName0)) {
                // This could happen when the date used is in DST,
                // because TimeZone.getDisplayName(ULocale) may use
                // localized GMT format for the time zone's standard
                // time.
                if (tz.inDaylightTime(now)) {
                    // Try getDisplayName with daylight argument
                    displayName0 = tz.getDisplayName(true, TimeZone.LONG_GENERIC, locale);
                }
                if (!displayName1.equals(displayName0)) {
                    errln(locale.getDisplayName() + ", " + tz.getID() + 
                            ": expected " + displayName1 + " but got: " + displayName0);
                }
            }
        }
    }
}
 
Example 4
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test to see if DateFormat understands zone equivalency groups.  It
 * might seem that this should be a DateFormat test, but it's really a
 * TimeZone test -- the changes to DateFormat are minor.
 *
 * We use two known, zones that are equivalent, where one zone has
 * localized name data, and the other doesn't, in some locale.
 */
@Test
public void TestJ449() {
    // not used String str;

    // Modify the following three as necessary.  The two IDs must
    // specify two zones in the same equivalency group.  One must have
    // locale data in 'loc'; the other must not.
    String idWithLocaleData = "America/Los_Angeles";
    String idWithoutLocaleData = "PST"; // "US/Pacific";
    Locale loc = new Locale("en", "", "");

    TimeZone zoneWith = TimeZone.getTimeZone(idWithLocaleData);
    TimeZone zoneWithout = TimeZone.getTimeZone(idWithoutLocaleData);
    // Make sure we got valid zones
    if (!(zoneWith.getID().equals(idWithLocaleData) &&
          zoneWithout.getID().equals(idWithoutLocaleData))) {
        warnln("Fail: Unable to create zones");
    } else {
        GregorianCalendar calWith = new GregorianCalendar(zoneWith);
        GregorianCalendar calWithout = new GregorianCalendar(zoneWithout);
        SimpleDateFormat fmt =
            new SimpleDateFormat("MMM d yyyy hh:mm a zzz", loc);
        Date date = new Date(0L);
        fmt.setCalendar(calWith);
        String strWith = fmt.format(date);
        fmt.setCalendar(calWithout);
        String strWithout = fmt.format(date);
        if (strWith.equals(strWithout)) {
            logln("Ok: " + idWithLocaleData + " -> " +
                  strWith + "; " + idWithoutLocaleData + " -> " +
                  strWithout);
        } else {
            errln("FAIL: " + idWithLocaleData + " -> " +
                  strWith + "; " + idWithoutLocaleData + " -> " +
                  strWithout);
        }
    }
}
 
Example 5
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Calendar and Date HOUR broken. If HOUR is out-of-range, Calendar and Date
 * classes will misbehave.
 */
@Test
public void Test4162587() {
    TimeZone tz = TimeZone.getTimeZone("PST");
    TimeZone.setDefault(tz);
    GregorianCalendar cal = new GregorianCalendar(tz);
    Date d;
    
    for (int i=0; i<5; ++i) {
        if (i>0) logln("---");

        cal.clear();
        cal.set(1998, Calendar.APRIL, 5, i, 0);
        d = cal.getTime();
        String s0 = d.toString();
        logln("0 " + i + ": " + s0);

        cal.clear();
        cal.set(1998, Calendar.APRIL, 4, i+24, 0);
        d = cal.getTime();
        String sPlus = d.toString();
        logln("+ " + i + ": " + sPlus);

        cal.clear();
        cal.set(1998, Calendar.APRIL, 6, i-24, 0);
        d = cal.getTime();
        String sMinus = d.toString();
        logln("- " + i + ": " + sMinus);

        if (!s0.equals(sPlus) || !s0.equals(sMinus)) {
            errln("Fail: All three lines must match");
        }
    }
}
 
Example 6
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestFreezable() {
    // Test zones - initially thawed
    TimeZone[] ZA1 = {
        TimeZone.getDefault(),
        TimeZone.getTimeZone("America/Los_Angeles", TimeZone.TIMEZONE_ICU),
        TimeZone.getTimeZone("America/Los_Angeles", TimeZone.TIMEZONE_JDK),
        new SimpleTimeZone(0, "stz"),
        new RuleBasedTimeZone("rbtz", new InitialTimeZoneRule("rbtz0", 0, 0)),
        VTimeZone.create("America/New_York"),
    };

    checkThawed(ZA1, "ZA1");
    // freeze
    for (int i = 0; i < ZA1.length; i++) {
        ZA1[i].freeze();
    }
    checkFrozen(ZA1, "ZA1(frozen)");

    // Test zones - initially frozen
    final TimeZone[] ZA2 = {
        TimeZone.GMT_ZONE,
        TimeZone.UNKNOWN_ZONE,
        TimeZone.getFrozenTimeZone("America/Los_Angeles"),
        new SimpleTimeZone(3600000, "frz_stz").freeze(),
        new RuleBasedTimeZone("frz_rbtz", new InitialTimeZoneRule("frz_rbtz0", 3600000, 0)).freeze(),
        VTimeZone.create("Asia/Tokyo").freeze(),
    };

    checkFrozen(ZA2, "ZA2");
    TimeZone[] ZA2_thawed = new TimeZone[ZA2.length];
    // create thawed clone
    for (int i = 0; i < ZA2_thawed.length; i++) {
        ZA2_thawed[i] = ZA2[i].cloneAsThawed();
    }
    checkThawed(ZA2_thawed, "ZA2(thawed)");

}
 
Example 7
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * TimeZone broken in last hour of year
 */
@Test
public void Test4173604() {
    TimeZone pst = TimeZone.getTimeZone("PST");
    int o22 = pst.getOffset(1, 1998, 11, 31, Calendar.THURSDAY, 22*60*60*1000);
    int o23 = pst.getOffset(1, 1998, 11, 31, Calendar.THURSDAY, 23*60*60*1000);
    int o00 = pst.getOffset(1, 1999, 0, 1, Calendar.FRIDAY, 0);
    if (o22 != o23 || o22 != o00) {
        errln("Offsets should be the same (for PST), but got: " +
              "12/31 22:00 " + o22 +
              ", 12/31 23:00 " + o23 +
              ", 01/01 00:00 " + o00);
    }

    GregorianCalendar cal = new GregorianCalendar();
    cal.setTimeZone(pst);
    cal.clear();
    cal.set(1998, Calendar.JANUARY, 1);
    int lastDST = cal.get(Calendar.DST_OFFSET);
    int transitions = 0;
    int delta = 5;
    while (cal.get(Calendar.YEAR) < 2000) {
        cal.add(Calendar.MINUTE, delta);
        if (cal.get(Calendar.DST_OFFSET) != lastDST) {
            ++transitions;
            Calendar t = (Calendar)cal.clone();
            t.add(Calendar.MINUTE, -delta);
            logln(t.getTime() + "  " + t.get(Calendar.DST_OFFSET));
            logln(cal.getTime() + "  " + (lastDST=cal.get(Calendar.DST_OFFSET)));
        }
    }
    if (transitions != 4) {
        errln("Saw " + transitions + " transitions; should have seen 4");
    }
}
 
Example 8
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void Test4151429() {
    try {
        TimeZone tz = TimeZone.getTimeZone("GMT");
        /*String name =*/ tz.getDisplayName(true, Integer.MAX_VALUE,
                                        Locale.getDefault());
        errln("IllegalArgumentException not thrown by TimeZone.getDisplayName()");
    } catch(IllegalArgumentException e) {
        System.out.print("");
    }
}
 
Example 9
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void Test4109314() {
    GregorianCalendar testCal = (GregorianCalendar)Calendar.getInstance();
    TimeZone PST = TimeZone.getTimeZone("PST");
    java.util.Calendar tempcal = java.util.Calendar.getInstance();
    tempcal.clear();
    tempcal.set(1998,Calendar.APRIL,4,22,0);
    Date d1 = tempcal.getTime();
    tempcal.set(1998,Calendar.APRIL,5,6,0);
    Date d2 = tempcal.getTime();
    tempcal.set(1998,Calendar.OCTOBER,24,22,0);
    Date d3 = tempcal.getTime();
    tempcal.set(1998,Calendar.OCTOBER,25,6,0);
    Date d4 = tempcal.getTime();
    Object[] testData = {
        PST, d1, d2,
        PST, d3, d4,
    };
    boolean pass=true;
    for (int i=0; i<testData.length; i+=3) {
        testCal.setTimeZone((TimeZone) testData[i]);
        long t = ((Date)testData[i+1]).getTime();
        Date end = (Date) testData[i+2];
        while (t < end.getTime()) {
            testCal.setTime(new Date(t));
            if (!checkCalendar314(testCal, (TimeZone) testData[i]))
                pass = false;
            t += 60*60*1000L;
        }
    }
    if (!pass) errln("Fail: TZ API inconsistent");
}
 
Example 10
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * The expected behavior of TimeZone around the boundaries is:
 * (Assume transition time of 2:00 AM)
 *    day of onset 1:59 AM STD  = display name 1:59 AM ST
 *                 2:00 AM STD  = display name 3:00 AM DT
 *    day of end   0:59 AM STD  = display name 1:59 AM DT
 *                 1:00 AM STD  = display name 1:00 AM ST
 */
@Test
public void Test4084933() {
    TimeZone tz = TimeZone.getTimeZone("PST");

    long offset1 = tz.getOffset(1,
        1997, Calendar.OCTOBER, 26, Calendar.SUNDAY, (2*60*60*1000));
    long offset2 = tz.getOffset(1,
        1997, Calendar.OCTOBER, 26, Calendar.SUNDAY, (2*60*60*1000)-1);

    long offset3 = tz.getOffset(1,
        1997, Calendar.OCTOBER, 26, Calendar.SUNDAY, (1*60*60*1000));
    long offset4 = tz.getOffset(1,
        1997, Calendar.OCTOBER, 26, Calendar.SUNDAY, (1*60*60*1000)-1);

    /*
     *  The following was added just for consistency.  It shows that going *to* Daylight
     *  Savings Time (PDT) does work at 2am.
     */

    long offset5 = tz.getOffset(1,
        1997, Calendar.APRIL, 6, Calendar.SUNDAY, (2*60*60*1000));
    long offset6 = tz.getOffset(1,
        1997, Calendar.APRIL, 6, Calendar.SUNDAY, (2*60*60*1000)-1);

    long offset7 = tz.getOffset(1,
        1997, Calendar.APRIL, 6, Calendar.SUNDAY, (1*60*60*1000));
    long offset8 = tz.getOffset(1,
        1997, Calendar.APRIL, 6, Calendar.SUNDAY, (1*60*60*1000)-1);

    long SToffset = -8 * 60*60*1000L;
    long DToffset = -7 * 60*60*1000L;
    if (offset1 != SToffset || offset2 != SToffset ||
        offset3 != SToffset || offset4 != DToffset ||
        offset5 != DToffset || offset6 != SToffset ||
        offset7 != SToffset || offset8 != SToffset)
        warnln("Fail: TimeZone misbehaving");
}
 
Example 11
Source File: AstroTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
    public void TestBasics() {
        // Check that our JD computation is the same as the book's (p. 88)
        CalendarAstronomer astro = new CalendarAstronomer();
        GregorianCalendar cal3 = new GregorianCalendar(TimeZone.getTimeZone("GMT"), Locale.US);
        DateFormat d3 = DateFormat.getDateTimeInstance(cal3, DateFormat.MEDIUM,DateFormat.MEDIUM,Locale.US);
        cal3.clear();
        cal3.set(Calendar.YEAR, 1980);
        cal3.set(Calendar.MONTH, Calendar.JULY);
        cal3.set(Calendar.DATE, 27);
        astro.setDate(cal3.getTime());
        double jd = astro.getJulianDay() - 2447891.5;
        double exp = -3444;
        if (jd == exp) {
            logln(d3.format(cal3.getTime()) + " => " + jd);
        } else {
            errln("FAIL: " + d3.format(cal3.getTime()) + " => " + jd +
                  ", expected " + exp);
        }


//        cal3.clear();
//        cal3.set(cal3.YEAR, 1990);
//        cal3.set(cal3.MONTH, Calendar.JANUARY);
//        cal3.set(cal3.DATE, 1);
//        cal3.add(cal3.DATE, -1);
//        astro.setDate(cal3.getTime());
//        astro.foo();
    }
 
Example 12
Source File: TimeZoneRuleTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private long getUTCMillis(int year, int month, int dayOfMonth) {
    if (utcCal == null) {
        utcCal = new GregorianCalendar(TimeZone.getTimeZone("UTC"), ULocale.ROOT);
    }
    utcCal.clear();
    utcCal.set(year, month, dayOfMonth);
    return utcCal.getTimeInMillis();
}
 
Example 13
Source File: DateTimeGeneratorTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void TestReplacingZoneString() {
    Date testDate = new Date();
    TimeZone testTimeZone = TimeZone.getTimeZone("America/New_York");
    TimeZone bogusTimeZone = new SimpleTimeZone(1234, "Etc/Unknown");
    Calendar calendar = Calendar.getInstance();
    ParsePosition parsePosition = new ParsePosition(0);

    ULocale[] locales = ULocale.getAvailableLocales();
    int count = 0;
    for (int i = 0; i < locales.length; ++i) {
        // skip the country locales unless we are doing exhaustive tests
        if (getExhaustiveness() < 6) {
            if (locales[i].getCountry().length() > 0) {
                continue;
            }
        }
        count++;
        // Skipping some test case in the non-exhaustive mode to reduce the test time
        //ticket#6503
        if(getExhaustiveness()<=5 && count%3!=0){
            continue;
        }
        logln(locales[i].toString());
        DateTimePatternGenerator dtpgen
        = DateTimePatternGenerator.getInstance(locales[i]);

        for (int style1 = DateFormat.FULL; style1 <= DateFormat.SHORT; ++style1) {
            final SimpleDateFormat oldFormat = (SimpleDateFormat) DateFormat.getTimeInstance(style1, locales[i]);
            String pattern = oldFormat.toPattern();
            String newPattern = dtpgen.replaceFieldTypes(pattern, "VVVV"); // replaceZoneString(pattern, "VVVV");
            if (newPattern.equals(pattern)) {
                continue;
            }
            // verify that it roundtrips parsing
            SimpleDateFormat newFormat = new SimpleDateFormat(newPattern, locales[i]);
            newFormat.setTimeZone(testTimeZone);
            String formatted = newFormat.format(testDate);
            calendar.setTimeZone(bogusTimeZone);
            parsePosition.setIndex(0);
            newFormat.parse(formatted, calendar, parsePosition);
            if (parsePosition.getErrorIndex() >= 0) {
                errln("Failed parse with VVVV:\t" + locales[i] + ",\t\"" + pattern + "\",\t\"" + newPattern + "\",\t\"" + formatted.substring(0,parsePosition.getErrorIndex()) + "{}" + formatted.substring(parsePosition.getErrorIndex()) + "\"");
            } else if (!calendar.getTimeZone().getID().equals(testTimeZone.getID())) {
                errln("Failed timezone roundtrip with VVVV:\t" + locales[i] + ",\t\"" + pattern + "\",\t\"" + newPattern + "\",\t\"" + formatted + "\",\t" + calendar.getTimeZone().getID() + " != " + testTimeZone.getID());
            } else {
                logln(locales[i] + ":\t\"" + pattern + "\" => \t\"" + newPattern + "\"\t" + formatted);
            }
        }
    }
}
 
Example 14
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void TestObservesDaylightTime() {
    boolean observesDaylight;
    long current = System.currentTimeMillis();

    // J2ObjC change: time zones going through adjustments are problematic when comparing
    // the ICU tz data vs. the operating system tz data.
    Set<String> unstableTzids = new HashSet<>();
    // https://github.com/eggert/tz/blob/379f7ba9b81eee97f0209a322540b4a522122b5d/africa#L847
    unstableTzids.add("Africa/Casablanca");
    unstableTzids.add("Africa/El_Aaiun");

    String[] tzids = TimeZone.getAvailableIDs();
    for (String tzid : tzids) {
        // OlsonTimeZone
        TimeZone tz = TimeZone.getTimeZone(tzid, TimeZone.TIMEZONE_ICU);
        observesDaylight = tz.observesDaylightTime();
        if (observesDaylight != isDaylightTimeAvailable(tz, current)) {
            errln("Fail: [OlsonTimeZone] observesDaylightTime() returned " + observesDaylight + " for " + tzid);
        }

        // RuleBasedTimeZone
        RuleBasedTimeZone rbtz = createRBTZ((BasicTimeZone)tz, current);
        boolean observesDaylightRBTZ = rbtz.observesDaylightTime();
        if (observesDaylightRBTZ != isDaylightTimeAvailable(rbtz, current)) {
            errln("Fail: [RuleBasedTimeZone] observesDaylightTime() returned " + observesDaylightRBTZ + " for " + rbtz.getID());
        } else if (observesDaylight != observesDaylightRBTZ) {
            errln("Fail: RuleBasedTimeZone " + rbtz.getID() + " returns " + observesDaylightRBTZ + ", but different from match OlsonTimeZone");
        }

        // JavaTimeZone
        tz = TimeZone.getTimeZone(tzid, TimeZone.TIMEZONE_JDK);
        observesDaylight = tz.observesDaylightTime();
        if (!unstableTzids.contains(tzid)
            && observesDaylight != isDaylightTimeAvailable(tz, current)) {
            errln("Fail: [JavaTimeZone] observesDaylightTime() returned " + observesDaylight + " for " + tzid);
        }

        // VTimeZone
        tz = VTimeZone.getTimeZone(tzid);
        observesDaylight = tz.observesDaylightTime();
        if (observesDaylight != isDaylightTimeAvailable(tz, current)) {
            errln("Fail: [VTimeZone] observesDaylightTime() returned " + observesDaylight + " for " + tzid);
        }
    }

    // SimpleTimeZone
    SimpleTimeZone[] stzs = {
        new SimpleTimeZone(0, "STZ0"),
        new SimpleTimeZone(-5*60*60*1000, "STZ-5D", Calendar.MARCH, 2, Calendar.SUNDAY, 2*60*60*1000,
                Calendar.NOVEMBER, 1, Calendar.SUNDAY, 2*60*60*1000),
    };
    for (SimpleTimeZone stz : stzs) {
        observesDaylight = stz.observesDaylightTime();
        if (observesDaylight != isDaylightTimeAvailable(stz, current)) {
            errln("Fail: [SimpleTimeZone] observesDaylightTime() returned " + observesDaylight + " for " + stz.getID());
        }
    }
}
 
Example 15
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void Test4073209() {
    TimeZone z1 = TimeZone.getTimeZone("PST");
    TimeZone z2 = TimeZone.getTimeZone("PST");
    if (z1 == z2) errln("Fail: TimeZone should return clones");
}
 
Example 16
Source File: TimeZoneAliasTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private Zone(String id) { // for interal use only; use make instead!
    zone = TimeZone.getTimeZone(id);
    this.id = id;
    
    // get aliases
    int equivCount = TimeZone.countEquivalentIDs(id);
    for (int j = 0; j < equivCount; ++j) {
        String altID = TimeZone.getEquivalentID(id, j);
        if (altID.equals(id)) continue;
        purportedAliases.add(altID);
    }

    // find inflexion points; times where the offset changed
    long lastDate = endDate;
    if (zone.getOffset(lastDate) < zone.getOffset(endDate2)) lastDate = endDate2;
    maxRecentOffset = minRecentOffset = minOffset = maxOffset = zone.getOffset(lastDate);

    inflectionPoints.add(new Long(lastDate));
    int lastOffset = zone.getOffset(endDate);
    long lastInflection = endDate;
    
    // we do a gross search, then narrow in when we find a difference from the last one
    for (long currentDate = endDate; currentDate >= startDate; currentDate -= GROSS_PERIOD) {
        int currentOffset = zone.getOffset(currentDate);
        if (currentOffset != lastOffset) { // Binary Search
            if (currentOffset < minOffset) minOffset = currentOffset;
            if (currentOffset > maxOffset) maxOffset = currentOffset;
            if (lastInflection >= recentLimit) {
                if (currentOffset < minRecentOffset) minRecentOffset = currentOffset;
                if (currentOffset > maxRecentOffset) maxRecentOffset = currentOffset;
            }
            long low = currentDate;
            long high = lastDate;
            while (low - high > EPSILON) {
                long mid = (high + low)/2;
                int midOffset = zone.getOffset(mid);
                if (midOffset == low) {
                    low = mid;
                } else {
                    high = mid;
                }
            }
            inflectionPoints.add(new Long(low));
            lastInflection = low;
        }
        lastOffset = currentOffset;
    }
    inflectionPoints.add(new Long(startDate)); // just to cap it off for comparisons.
}
 
Example 17
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void TestSetDefault() {
    java.util.TimeZone save = java.util.TimeZone.getDefault();

    /*
     * America/Caracs (Venezuela) changed the base offset from -4:00 to
     * -4:30 on Dec 9, 2007.
     */

    TimeZone icuCaracas = TimeZone.getTimeZone("America/Caracas", TimeZone.TIMEZONE_ICU);
    java.util.TimeZone jdkCaracas = java.util.TimeZone.getTimeZone("America/Caracas");

    // Set JDK America/Caracas as the default
    java.util.TimeZone.setDefault(jdkCaracas);

    java.util.Calendar jdkCal = java.util.Calendar.getInstance();
    jdkCal.clear();
    jdkCal.set(2007, java.util.Calendar.JANUARY, 1);

    int rawOffset = jdkCal.get(java.util.Calendar.ZONE_OFFSET);
    int dstSavings = jdkCal.get(java.util.Calendar.DST_OFFSET);

    int[] offsets = new int[2];
    icuCaracas.getOffset(jdkCal.getTime().getTime()/*jdkCal.getTimeInMillis()*/, false, offsets);

    boolean isTimeZoneSynchronized = true;

    if (rawOffset != offsets[0] || dstSavings != offsets[1]) {
        // JDK time zone rule is out of sync...
        logln("Rule for JDK America/Caracas is not same with ICU.  Skipping the rest.");
        isTimeZoneSynchronized = false;
    }

    if (isTimeZoneSynchronized) {
        // If JDK America/Caracas uses the same rule with ICU,
        // the following code should work well.
        TimeZone.setDefault(icuCaracas);

        // Create a new JDK calendar instance again.
        // This calendar should reflect the new default
        // set by ICU TimeZone#setDefault.
        jdkCal = java.util.Calendar.getInstance();
        jdkCal.clear();
        jdkCal.set(2007, java.util.Calendar.JANUARY, 1);

        rawOffset = jdkCal.get(java.util.Calendar.ZONE_OFFSET);
        dstSavings = jdkCal.get(java.util.Calendar.DST_OFFSET);

        if (rawOffset != offsets[0] || dstSavings != offsets[1]) {
            errln("ERROR: Got offset [raw:" + rawOffset + "/dst:" + dstSavings
                      + "] Expected [raw:" + offsets[0] + "/dst:" + offsets[1] + "]");
        }
    }

    // Restore the original JDK time zone
    java.util.TimeZone.setDefault(save);
}
 
Example 18
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void TestFebruary() {
    // Time zone with daylight savings time from the first Sunday in November
    // to the last Sunday in February.
    // Similar to the new rule for Brazil (Sao Paulo) in tzdata2006n.
    //
    // Note: In tzdata2007h, the rule had changed, so no actual zones uses
    // lastSun in Feb anymore.
    SimpleTimeZone tz1 = new SimpleTimeZone(
                       -3 * MILLIS_PER_HOUR,                    // raw offset: 3h before (west of) GMT
                       "nov-feb",
                       Calendar.NOVEMBER, 1, Calendar.SUNDAY,   // start: November, first, Sunday
                       0,                                       //        midnight wall time
                       Calendar.FEBRUARY, -1, Calendar.SUNDAY,  // end:   February, last, Sunday
                       0);                                      //        midnight wall time

    // Now hardcode the same rules as for Brazil in tzdata 2006n, so that
    // we cover the intended code even when in the future zoneinfo hardcodes
    // these transition dates.
    SimpleTimeZone tz2= new SimpleTimeZone(
                       -3 * MILLIS_PER_HOUR,                    // raw offset: 3h before (west of) GMT
                       "nov-feb2",
                       Calendar.NOVEMBER, 1, -Calendar.SUNDAY,  // start: November, 1 or after, Sunday
                       0,                                       //        midnight wall time
                       Calendar.FEBRUARY, -29, -Calendar.SUNDAY,// end:   February, 29 or before, Sunday
                       0);                                      //        midnight wall time

    // Gregorian calendar with the UTC time zone for getting sample test date/times.
    GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("Etc/GMT"));
    // "Unable to create the UTC calendar: %s"

    int[] data = {
        // UTC time (6 fields) followed by
        // expected time zone offset in hours after GMT (negative=before GMT).
        // int year, month, day, hour, minute, second, offsetHours
        2006, Calendar.NOVEMBER,  5, 02, 59, 59, -3,
        2006, Calendar.NOVEMBER,  5, 03, 00, 00, -2,
        2007, Calendar.FEBRUARY, 25, 01, 59, 59, -2,
        2007, Calendar.FEBRUARY, 25, 02, 00, 00, -3,

        2007, Calendar.NOVEMBER,  4, 02, 59, 59, -3,
        2007, Calendar.NOVEMBER,  4, 03, 00, 00, -2,
        2008, Calendar.FEBRUARY, 24, 01, 59, 59, -2,
        2008, Calendar.FEBRUARY, 24, 02, 00, 00, -3,

        2008, Calendar.NOVEMBER,  2, 02, 59, 59, -3,
        2008, Calendar.NOVEMBER,  2, 03, 00, 00, -2,
        2009, Calendar.FEBRUARY, 22, 01, 59, 59, -2,
        2009, Calendar.FEBRUARY, 22, 02, 00, 00, -3,

        2009, Calendar.NOVEMBER,  1, 02, 59, 59, -3,
        2009, Calendar.NOVEMBER,  1, 03, 00, 00, -2,
        2010, Calendar.FEBRUARY, 28, 01, 59, 59, -2,
        2010, Calendar.FEBRUARY, 28, 02, 00, 00, -3
    };

    TimeZone timezones[] = { tz1, tz2 };

    TimeZone tz;
    Date dt;
    int t, i, raw, dst;
    int[] offsets = new int[2]; // raw = offsets[0], dst = offsets[1]
    for (t = 0; t < timezones.length; ++t) {
        tz = timezones[t];
        for (i = 0; i < data.length; i+=7) {
            gc.set(data[i], data[i+1], data[i+2],
                   data[i+3], data[i+4], data[i+5]);
            dt = gc.getTime();
            tz.getOffset(dt.getTime(), false, offsets);
            raw = offsets[0];
            dst = offsets[1];
            if ((raw + dst) != data[i+6] * MILLIS_PER_HOUR) {
                errln("test case " + t + "." + (i/7) + ": " +
                      "tz.getOffset(" + data[i] + "-" + (data[i+1] + 1) + "-" + data[i+2] + " " +
                      data[i+3] + ":" + data[i+4] + ":" + data[i+5] +
                      ") returns " + raw + "+" + dst + " != " + data[i+6] * MILLIS_PER_HOUR);
            }
        }
    }
}
 
Example 19
Source File: GlobalizationPreferencesTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void TestTimeZone() {
    GlobalizationPreferences gp = new GlobalizationPreferences();

    // Set locale - zh_CN 
    logln("Set locale - zh_CN");
    gp.setLocale(new ULocale("zh_CN"));
    TimeZone tz = gp.getTimeZone();
    String tzid = tz.getID();
    if (!tzid.equals("Asia/Shanghai")) {
        errln("FAIL: Time zone ID is " + tzid + " Expected: Asia/Shanghai");
    }

    // Set locale - en
    logln("Set locale - en");
    gp.setLocale(new ULocale("en"));
    tz = gp.getTimeZone();
    tzid = tz.getID();
    if (!tzid.equals("America/New_York")) {
        errln("FAIL: Time zone ID is " + tzid + " Expected: America/New_York");
    }

    // Set territory - GB
    logln("Set territory - GB");
    gp.setTerritory("GB");
    tz = gp.getTimeZone();
    tzid = tz.getID();
    if (!tzid.equals("Europe/London")) {
        errln("FAIL: Time zone ID is " + tzid + " Expected: Europe/London");
    }

    // Check if getTimeZone returns a safe clone
    tz.setID("Bad_ID");
    tz = gp.getTimeZone();
    tzid = tz.getID();
    if (!tzid.equals("Europe/London")) {
        errln("FAIL: Time zone ID is " + tzid + " Expected: Europe/London");
    }

    // Set explicit time zone
    TimeZone jst = TimeZone.getTimeZone("Asia/Tokyo");
    String customJstId = "Japan_Standard_Time";
    jst.setID(customJstId);
    gp.setTimeZone(jst);
    tz = gp.getTimeZone();
    tzid = tz.getID();
    if (!tzid.equals(customJstId)) {
        errln("FAIL: Time zone ID is " + tzid + " Expected: " + customJstId);
    }

    // Freeze
    logln("Freeze this object");
    TimeZone cst = TimeZone.getTimeZone("Europe/Paris");
    boolean bFrozen = false;
    gp.freeze();
    try {
        gp.setTimeZone(cst);
    } catch (UnsupportedOperationException uoe) {
        logln("setTimeZone is blocked");
        bFrozen = true;
    }
    if (!bFrozen) {
        errln("FAIL: setTimeZone must be blocked");
    }

    // Modifiable clone
    logln("cloneAsThawed");
    GlobalizationPreferences gp1 = (GlobalizationPreferences)gp.cloneAsThawed();
    tz = gp1.getTimeZone();
    tzid = tz.getID();
    if (!tzid.equals(customJstId)) {
        errln("FAIL: Time zone ID is " + tzid + " Expected: " + customJstId);
    }

    // Set explicit time zone
    gp1.setTimeZone(cst);
    tz = gp1.getTimeZone();
    tzid = tz.getID();
    if (!tzid.equals(cst.getID())) {
        errln("FAIL: Time zone ID is " + tzid + " Expected: " + cst.getID());
    }        
}
 
Example 20
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test
public void Test_GEec() {
    class PatternAndResult {
        private String pattern;
        private String result;
        PatternAndResult(String pat, String res) {
            pattern = pat;
            result = res;
        }
        public String getPattern()  { return pattern; }
        public String getResult()  { return result; }
    }
    final PatternAndResult[] tests = {
        new PatternAndResult( "dd MMM yyyy GGG",   "02 Jul 2008 AD" ),
        new PatternAndResult( "dd MMM yyyy GGGGG", "02 Jul 2008 A" ),
        new PatternAndResult( "e dd MMM yyyy",     "4 02 Jul 2008" ),
        new PatternAndResult( "ee dd MMM yyyy",    "04 02 Jul 2008" ),
        new PatternAndResult( "c dd MMM yyyy",     "4 02 Jul 2008" ),
        new PatternAndResult( "cc dd MMM yyyy",    "4 02 Jul 2008" ),
        new PatternAndResult( "eee dd MMM yyyy",   "Wed 02 Jul 2008" ),
        new PatternAndResult( "EEE dd MMM yyyy",   "Wed 02 Jul 2008" ),
        new PatternAndResult( "EE dd MMM yyyy",    "Wed 02 Jul 2008" ),
        new PatternAndResult( "eeee dd MMM yyyy",  "Wednesday 02 Jul 2008" ),
        new PatternAndResult( "eeeee dd MMM yyyy", "W 02 Jul 2008" ),
        new PatternAndResult( "e ww YYYY",         "4 27 2008" ),
        new PatternAndResult( "c ww YYYY",         "4 27 2008" ),
    };
    ULocale loc = ULocale.ENGLISH;
    TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
    Calendar cal = new GregorianCalendar(tz, loc);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd", loc);
    for ( int i = 0; i < tests.length; i++ ) {
        PatternAndResult item = tests[i];
        dateFormat.applyPattern( item.getPattern() );
        cal.set(2008, 6, 2, 5, 0); // 2008 July 02 5 AM PDT
        StringBuffer buf = new StringBuffer(32);
        FieldPosition fp = new FieldPosition(DateFormat.YEAR_FIELD);
        dateFormat.format(cal, buf, fp);
        if ( buf.toString().compareTo(item.getResult()) != 0 ) {
            errln("for pattern " + item.getPattern() + ", expected " + item.getResult() + ", got " + buf );
        }
        ParsePosition pos = new ParsePosition(0);
        dateFormat.parse( item.getResult(), cal, pos);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DATE);
        if ( year != 2008 || month != 6 || day != 2 ) {
            errln("use pattern " + item.getPattern() + " to parse " + item.getResult() +
                    ", expected y2008 m6 d2, got " + year + " " + month + " " + day );
        }
    }
}