android.icu.util.TimeZone Java Examples

The following examples show how to use android.icu.util.TimeZone. 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: JavaTimeZone.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of JavaTimeZone with the given timezone ID.
 * @param id A timezone ID, either a system ID or a custom ID.
 * @return An instance of JavaTimeZone for the given ID, or null
 * when the ID cannot be understood.
 */
public static JavaTimeZone createTimeZone(String id) {
    java.util.TimeZone jtz = null;

    if (AVAILABLESET.contains(id)) {
        jtz = java.util.TimeZone.getTimeZone(id);
    }

    if (jtz == null) {
        // Use ICU's canonical ID mapping
        boolean[] isSystemID = new boolean[1];
        String canonicalID = TimeZone.getCanonicalID(id, isSystemID);
        if (isSystemID[0] && AVAILABLESET.contains(canonicalID)) {
            jtz = java.util.TimeZone.getTimeZone(canonicalID);
        }
    }

    if (jtz == null) {
        return null;
    }

    return new JavaTimeZone(jtz, id);
}
 
Example #2
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void Test4071385() {
// work around bug for jdk1.4 on solaris 2.6, which uses funky timezone
// names
// jdk1.4.1 will drop support for 2.6 so we should be ok when it comes out
java.util.TimeZone javazone = java.util.TimeZone.getTimeZone("GMT");
TimeZone icuzone = TimeZone.getTimeZone("GMT");

    Calendar cal = Calendar.getInstance(icuzone);
    java.util.Calendar tempcal = java.util.Calendar.getInstance(javazone);
    tempcal.clear();
    tempcal.set(1998, Calendar.JUNE, 24);
    cal.setTime(tempcal.getTime());
    cal.set(Calendar.MONTH, Calendar.NOVEMBER); // change a field
    logln(cal.getTime().toString());
    tempcal.set(1998, Calendar.NOVEMBER, 24);
    if (!cal.getTime().equals(tempcal.getTime()))
        errln("Fail");
}
 
Example #3
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void Test4061476() {
    SimpleDateFormat fmt = new SimpleDateFormat("ddMMMyy", Locale.UK);
    Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"), 
                                                 Locale.UK);
    fmt.setCalendar(cal);
    try
        {
            Date date = fmt.parse("29MAY97");
            cal.setTime(date);
        }
    catch (Exception e) {
        System.out.print("");
    }
    cal.set(Calendar.HOUR_OF_DAY, 13);
    logln("Hour: "+cal.get(Calendar.HOUR_OF_DAY));
    cal.add(Calendar.HOUR_OF_DAY, 6);
    logln("Hour: "+cal.get(Calendar.HOUR_OF_DAY));
    if (cal.get(Calendar.HOUR_OF_DAY) != 19)
        errln("Fail: Want 19 Got " + cal.get(Calendar.HOUR_OF_DAY));
}
 
Example #4
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * TimeZone.getAvailableIDs(int) throws exception for certain values,
 * due to a faulty constant in TimeZone.java.
 */
@Test
public void Test4151406() {
    int max = 0;
    for (int h=-28; h<=30; ++h) {
        // h is in half-hours from GMT; rawoffset is in millis
        int rawoffset = h * 1800000;
        int hh = (h<0) ? -h : h;
        String hname = ((h<0) ? "GMT-" : "GMT+") +
            ((hh/2 < 10) ? "0" : "") +
            (hh/2) + ':' +
            ((hh%2==0) ? "00" : "30");
        try {
            String[] ids = TimeZone.getAvailableIDs(rawoffset);
            if (ids.length > max) max = ids.length;
            logln(hname + ' ' + ids.length +
                  ((ids.length > 0) ? (" e.g. " + ids[0]) : ""));
        } catch (Exception e) {
            errln(hname + ' ' + "Fail: " + e);
        }
    }
    logln("Maximum zones per offset = " + max);
}
 
Example #5
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestHashCode() {
    String[] ids = TimeZone.getAvailableIDs();

    for (String id: ids) {
        TimeZone tz1 = TimeZone.getTimeZone(id);
        TimeZone tz2 = TimeZone.getTimeZone(id);

        // hash code are same for the same time zone
        if (tz1.hashCode() != tz2.hashCode()) {
            errln("Fail: Two time zone instances for " + id + " have different hash values.");
        }
        // string representation should be also same
        /* J2ObjC: compare classes instead of string representations. The NSObject's description
         * includes the object's address (e.g. <AndroidIcuImplOlsonTimeZone: 0x7ffbbbf061d0>) */
        if (!tz1.getClass().equals(tz2.getClass())) {
            errln("Fail: Two time zone instances for " + id + " have different classes.");
        }
    }
}
 
Example #6
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Maximum value for YEAR field wrong.
 */
@Test
public void Test4145983() {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date[] DATES = { new Date(Long.MAX_VALUE), new Date(Long.MIN_VALUE) };
    for (int i=0; i<DATES.length; ++i) {
        calendar.setTime(DATES[i]);
        int year = calendar.get(Calendar.YEAR);
        int maxYear = calendar.getMaximum(Calendar.YEAR);
        if (year > maxYear) {
            errln("Failed for "+DATES[i].getTime()+" ms: year=" +
                  year + ", maxYear=" + maxYear);
        }
    }
}
 
Example #7
Source File: SimpleDateFormat.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Formats a date or time, which is the standard millis
 * since January 1, 1970, 00:00:00 GMT.
 * <p>Example: using the US locale:
 * "yyyy.MM.dd G 'at' HH:mm:ss zzz" -&gt;&gt; 1996.07.10 AD at 15:08:56 PDT
 * @param cal the calendar whose date-time value is to be formatted into a date-time string
 * @param toAppendTo where the new date-time text is to be appended
 * @param pos the formatting position. On input: an alignment field,
 * if desired. On output: the offsets of the alignment field.
 * @return the formatted date-time string.
 * @see DateFormat
 */
@Override
public StringBuffer format(Calendar cal, StringBuffer toAppendTo,
                           FieldPosition pos) {
    TimeZone backupTZ = null;
    if (cal != calendar && !cal.getType().equals(calendar.getType())) {
        // Different calendar type
        // We use the time and time zone from the input calendar, but
        // do not use the input calendar for field calculation.
        calendar.setTimeInMillis(cal.getTimeInMillis());
        backupTZ = calendar.getTimeZone();
        calendar.setTimeZone(cal.getTimeZone());
        cal = calendar;
    }
    StringBuffer result = format(cal, getContext(DisplayContext.Type.CAPITALIZATION), toAppendTo, pos, null);
    if (backupTZ != null) {
        // Restore the original time zone
        calendar.setTimeZone(backupTZ);
    }
    return result;
}
 
Example #8
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestEpochStartFields() {
    TimeZone z = TimeZone.getDefault();
    Calendar c = Calendar.getInstance();
    Date d = new Date(-z.getRawOffset());
    if (z.inDaylightTime(d)) {
        logln("Warning: Skipping test because " + d +
              " is in DST.");
    }
    else {
        c.setTime(d);
        c.setMinimalDaysInFirstWeek(1);
        for (int i=0; i<Calendar.ZONE_OFFSET; ++i) {
            if (c.get(i) != EPOCH_FIELDS[i])
                errln("Expected field " + i + " to have value " + EPOCH_FIELDS[i] +
                      "; saw " + c.get(i) + " instead");
        }
        if (c.get(Calendar.ZONE_OFFSET) != z.getRawOffset())
            errln("Expected field ZONE_OFFSET to have value " + z.getRawOffset() +
                  "; saw " + c.get(Calendar.ZONE_OFFSET) + " instead");
        if (c.get(Calendar.DST_OFFSET) != 0)
            errln("Expected field DST_OFFSET to have value 0" +
                  "; saw " + c.get(Calendar.DST_OFFSET) + " instead");
    }
}
 
Example #9
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestGetWindowsID() {
    String[][] TESTDATA = {
        {"America/New_York",        "Eastern Standard Time"},
        {"America/Montreal",        "Eastern Standard Time"},
        {"America/Los_Angeles",     "Pacific Standard Time"},
        {"America/Vancouver",       "Pacific Standard Time"},
        {"Asia/Shanghai",           "China Standard Time"},
        {"Asia/Chongqing",          "China Standard Time"},
        {"America/Indianapolis",    "US Eastern Standard Time"},            // CLDR canonical name
        {"America/Indiana/Indianapolis",    "US Eastern Standard Time"},    // tzdb canonical name
        {"Asia/Khandyga",           "Yakutsk Standard Time"},
        {"Australia/Eucla",         "Aus Central W. Standard Time"}, // Now Windows does have a mapping
        {"Bogus",                   null},
    };

    for (String[] data : TESTDATA) {
        String winID = TimeZone.getWindowsID(data[0]);
        assertEquals("Fail: ID=" + data[0], data[1], winID);
    }
}
 
Example #10
Source File: HolidayTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestEaster(){        
    // Verify that Easter is working. Should be April 20, 2014
    final Holiday h = new EasterHoliday("Easter Sunday");
    final Date beginApril = getDate(2014, Calendar.APRIL, 1);
    final Date endApril   = getDate(2014, Calendar.APRIL, 30);
    final Date expect     = getDate(2014, Calendar.APRIL, 20);
    final Date actual     = h.firstBetween(beginApril, endApril);
    
    if(actual == null) {
        errln("Error: Easter 2014 should be on " + expect + " but got null.");
    } else {
        Calendar c = Calendar.getInstance(TimeZone.GMT_ZONE, Locale.US);
        c.setTime(actual);
        assertEquals("Easter's year:  ", 2014, c.get(Calendar.YEAR));
        assertEquals("Easter's month: ", Calendar.APRIL, c.get(Calendar.MONTH));
        assertEquals("Easter's date:  ", 20, c.get(Calendar.DATE));
    }
}
 
Example #11
Source File: ZoneMeta.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an immutable set of system time zone IDs.
 * Etc/Unknown is excluded.
 * @return An immutable set of system time zone IDs.
 */
private static synchronized Set<String> getSystemZIDs() {
    Set<String> systemZones = null;
    if (REF_SYSTEM_ZONES != null) {
        systemZones = REF_SYSTEM_ZONES.get();
    }
    if (systemZones == null) {
        Set<String> systemIDs = new TreeSet<String>();
        String[] allIDs = getZoneIDs();
        for (String id : allIDs) {
            // exclude Etc/Unknown
            if (id.equals(TimeZone.UNKNOWN_ZONE_ID)) {
                continue;
            }
            systemIDs.add(id);
        }
        systemZones = Collections.unmodifiableSet(systemIDs);
        REF_SYSTEM_ZONES = new SoftReference<Set<String>>(systemZones);
    }
    return systemZones;
}
 
Example #12
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestGetIDForWindowsID() {
    final String[][] TESTDATA = {
        {"Eastern Standard Time",   null,   "America/New_York"},
        {"Eastern Standard Time",   "US",   "America/New_York"},
        {"Eastern Standard Time",   "CA",   "America/Toronto"},
        {"Eastern Standard Time",   "CN",   "America/New_York"},
        {"China Standard Time",     null,   "Asia/Shanghai"},
        {"China Standard Time",     "CN",   "Asia/Shanghai"},
        {"China Standard Time",     "HK",   "Asia/Hong_Kong"},
        {"Mid-Atlantic Standard Time",  null,   null}, // No tz database mapping
        {"Bogus",                   null,   null},
    };

    for (String[] data : TESTDATA) {
        String id = TimeZone.getIDForWindowsID(data[0], data[1]);
        assertEquals("Fail: Windows ID=" + data[0] + ", Region=" + data[1],
                data[2], id);
    }
}
 
Example #13
Source File: TimeZoneGenericNames.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a collection of time zone display name matches for the specified types in the
 * given text at the given offset. This method only finds matches from the local trie,
 * that contains 1) generic location names and 2) long/short generic partial location names,
 * used by this object.
 * @param text the text
 * @param start the start offset in the text
 * @param types the set of name types.
 * @return A collection of match info.
 */
private synchronized Collection<GenericMatchInfo> findLocal(String text, int start, EnumSet<GenericNameType> types) {
    GenericNameSearchHandler handler = new GenericNameSearchHandler(types);
    _gnamesTrie.find(text, start, handler);
    if (handler.getMaxMatchLen() == (text.length() - start) || _gnamesTrieFullyLoaded) {
        // perfect match
        return handler.getMatches();
    }

    // All names are not yet loaded into the local trie.
    // Load all available names into the trie. This could be very heavy.

    Set<String> tzIDs = TimeZone.getAvailableIDs(SystemTimeZoneType.CANONICAL, null, null);
    for (String tzID : tzIDs) {
        loadStrings(tzID);
    }
    _gnamesTrieFullyLoaded = true;

    // now, try it again
    handler.resetResults();
    _gnamesTrie.find(text, start, handler);
    return handler.getMatches();
}
 
Example #14
Source File: TimeZoneGenericNames.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the display name of the time zone for the given name type
 * at the given date, or null if the display name is not available.
 *
 * @param tz the time zone
 * @param type the generic name type - see {@link GenericNameType}
 * @param date the date
 * @return the display name of the time zone for the given name type
 * at the given date, or null.
 */
public String getDisplayName(TimeZone tz, GenericNameType type, long date) {
    String name = null;
    String tzCanonicalID = null;
    switch (type) {
    case LOCATION:
        tzCanonicalID = ZoneMeta.getCanonicalCLDRID(tz);
        if (tzCanonicalID != null) {
            name = getGenericLocationName(tzCanonicalID);
        }
        break;
    case LONG:
    case SHORT:
        name = formatGenericNonLocationName(tz, type, date);
        if (name == null) {
            tzCanonicalID = ZoneMeta.getCanonicalCLDRID(tz);
            if (tzCanonicalID != null) {
                name = getGenericLocationName(tzCanonicalID);
            }
        }
        break;
    }
    return name;
}
 
Example #15
Source File: TimeZoneGenericNames.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Private method initializing the instance of <code>TimeZoneGenericName</code>.
 * This method should be called from a constructor and readObject.
 */
private void init() {
    if (_tznames == null) {
        _tznames = TimeZoneNames.getInstance(_locale);
    }
    _genericLocationNamesMap = new ConcurrentHashMap<String, String>();
    _genericPartialLocationNamesMap = new ConcurrentHashMap<String, String>();

    _gnamesTrie = new TextTrieMap<NameInfo>(true);
    _gnamesTrieFullyLoaded = false;

    // Preload zone strings for the default time zone
    TimeZone tz = TimeZone.getDefault();
    String tzCanonicalID = ZoneMeta.getCanonicalCLDRID(tz);
    if (tzCanonicalID != null) {
        loadStrings(tzCanonicalID);
    }
}
 
Example #16
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestGetOffsetDate() {
    Calendar cal = Calendar.getInstance();
    cal.set(1997, Calendar.JANUARY, 30);
    long date = cal.getTimeInMillis();

TimeZone tz_icu = TimeZone.getTimeZone("America/Los_Angeles");
int offset = tz_icu.getOffset(date);
if (offset != -28800000) {
    errln("expected offset -28800000, got: " + offset);
}

cal.set(1997, Calendar.JULY, 30);
date = cal.getTimeInMillis();
offset = tz_icu.getOffset(date);
if (offset != -25200000) {
    errln("expected offset -25200000, got: " + offset);
}
}
 
Example #17
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestJohannesburg() {
    String j_id="Africa/Johannesburg";
    TimeZone johannesburg = TimeZone.getTimeZone(j_id);
    final int ONE_HOUR = 60*60*1000;
    int expectedOffset = ONE_HOUR*2;  // GMT+2 - NO DST
    int offset = johannesburg.getOffset(GregorianCalendar.AD,2007,Calendar.JULY,5,Calendar.THURSDAY,0);        
    
    if(offset != expectedOffset) {
        errln("FAIL: zone " + j_id +" returned offset in July " + offset +", expected "+expectedOffset);
    } else {
        logln("OK: zone " + j_id +" returned offset in July: " + offset);
    }

    int offset2 = johannesburg.getOffset(GregorianCalendar.AD,2007,Calendar.DECEMBER,12,Calendar.WEDNESDAY,0);

    if(offset2 != expectedOffset) {
        errln("FAIL: zone " + j_id +" returned offset in December " + offset2 +", expected "+expectedOffset);
    } else {
        logln("OK: zone " + j_id +" returned offset in December: " + offset2);
    }
}
 
Example #18
Source File: TimeZoneTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestCoverage(){
    class StubTimeZone extends TimeZone{
        /**
         * For serialization
         */
        private static final long serialVersionUID = 8658654217433379343L;
        public int getOffset(int era, int year, int month, int day, int dayOfWeek, int milliseconds) {return 0;}
        public void setRawOffset(int offsetMillis) {}
        public int getRawOffset() {return 0;}
        public boolean useDaylightTime() {return false;}
        public boolean inDaylightTime(Date date) {return false;}
    } 
    StubTimeZone stub = new StubTimeZone();
    StubTimeZone stub2 = (StubTimeZone) stub.clone();
    if (stub.getDSTSavings() != 0){
        errln("TimeZone.getDSTSavings() should return 0");
    }
    if (!stub.hasSameRules(stub2)){
        errln("TimeZone.clone() object should hasSameRules");
 
    }
}
 
Example #19
Source File: OlsonTimeZone.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public TimeZone cloneAsThawed() {
    OlsonTimeZone tz = (OlsonTimeZone)super.cloneAsThawed();
    if (finalZone != null) {
        // TODO Do we really need this?
        finalZone.setID(getID());
        tz.finalZone = (SimpleTimeZone) finalZone.clone();
    }

    // Following data are read-only and never changed.
    // Therefore, shallow copies should be sufficient.
    //
    // transitionTimes64
    // typeMapData
    // typeOffsets

    tz.isFrozen = false;
    return tz;
}
 
Example #20
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 #21
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
void aux4064654(int yr, int mo, int dt, int hr, int mn, int sc) {
    Date date;
    Calendar gmtcal = Calendar.getInstance();
    gmtcal.setTimeZone(TimeZone.getTimeZone("Africa/Casablanca"));
    gmtcal.set(yr, mo-1, dt, hr, mn, sc);
    gmtcal.set(Calendar.MILLISECOND, 0);

    date = gmtcal.getTime();
    logln("date = "+date);

    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("America/Los_Angels"));
    cal.setTime(date);

    int offset = cal.getTimeZone().getOffset(cal.get(Calendar.ERA),
                                             cal.get(Calendar.YEAR),
                                             cal.get(Calendar.MONTH),
                                             cal.get(Calendar.DATE),
                                             cal.get(Calendar.DAY_OF_WEEK),
                                             cal.get(Calendar.MILLISECOND));

    logln("offset for "+date+"= "+(offset/1000/60/60.0) + "hr");

    int utc = ((cal.get(Calendar.HOUR_OF_DAY) * 60 +
                cal.get(Calendar.MINUTE)) * 60 +
               cal.get(Calendar.SECOND)) * 1000 +
        cal.get(Calendar.MILLISECOND) - offset;

    int expected = ((hr * 60 + mn) * 60 + sc) * 1000;

    if (utc != expected)
        errln("FAIL: Discrepancy of " +
              (utc - expected) + " millis = " +
              ((utc-expected)/1000/60/60.0) + " hr");
}
 
Example #22
Source File: MeasureFormat.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static DateFormat loadNumericDurationFormat(
        ICUResourceBundle r, String type) {
    r = r.getWithFallback(String.format("durationUnits/%s", type));
    // We replace 'h' with 'H' because 'h' does not make sense in the context of durations.
    DateFormat result = new SimpleDateFormat(r.getString().replace("h", "H"));
    result.setTimeZone(TimeZone.GMT_ZONE);
    return result;
}
 
Example #23
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void Test4040996() {
    try {
        String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
        SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
        Calendar calendar = new GregorianCalendar(pdt);

        calendar.set(Calendar.MONTH,3);
        calendar.set(Calendar.DAY_OF_MONTH,18);
        calendar.set(Calendar.SECOND, 30);

        logln("MONTH: " + calendar.get(Calendar.MONTH));
        logln("DAY_OF_MONTH: " + 
                           calendar.get(Calendar.DAY_OF_MONTH));
        logln("MINUTE: " + calendar.get(Calendar.MINUTE));
        logln("SECOND: " + calendar.get(Calendar.SECOND));

        calendar.add(Calendar.SECOND,6);
        //This will print out todays date for MONTH and DAY_OF_MONTH
        //instead of the date it was set to.
        //This happens when adding MILLISECOND or MINUTE also
        logln("MONTH: " + calendar.get(Calendar.MONTH));
        logln("DAY_OF_MONTH: " + 
                           calendar.get(Calendar.DAY_OF_MONTH));
        logln("MINUTE: " + calendar.get(Calendar.MINUTE));
        logln("SECOND: " + calendar.get(Calendar.SECOND));
        if (calendar.get(Calendar.MONTH) != 3 ||
            calendar.get(Calendar.DAY_OF_MONTH) != 18 ||
            calendar.get(Calendar.SECOND) != 36)
            errln("Fail: Calendar.add misbehaves");
    } catch (Exception e) {
        warnln("Could not load data. "+ e.getMessage());
    }
}
 
Example #24
Source File: IBMCalendarTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Make sure that when adding a day, we actually wind up in a
 * different day.  The DST adjustments we use to keep the hour
 * constant across DST changes can backfire and change the day.
 */
@Test
public void TestTimeZoneTransitionAdd() {
    Locale locale = Locale.US; // could also be CHINA
    SimpleDateFormat dateFormat =
        new SimpleDateFormat("MM/dd/yyyy HH:mm z", locale);

    String tz[] = TimeZone.getAvailableIDs();

    for (int z=0; z<tz.length; ++z) {
        TimeZone t = TimeZone.getTimeZone(tz[z]);
        dateFormat.setTimeZone(t);

        Calendar cal = Calendar.getInstance(t, locale);
        cal.clear();
        // Scan the year 2003, overlapping the edges of the year
        cal.set(Calendar.YEAR, 2002);
        cal.set(Calendar.MONTH, Calendar.DECEMBER);
        cal.set(Calendar.DAY_OF_MONTH, 25);

        for (int i=0; i<365+10; ++i) {
            Date yesterday = cal.getTime();
            int yesterday_day = cal.get(Calendar.DAY_OF_MONTH);
            cal.add(Calendar.DAY_OF_MONTH, 1);
            if (yesterday_day == cal.get(Calendar.DAY_OF_MONTH)) {
                errln(tz[z] + " " +
                      dateFormat.format(yesterday) + " +1d= " +
                      dateFormat.format(cal.getTime()));
            }
        }
    }
}
 
Example #25
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 #26
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 #27
Source File: TestCLDRVsICU.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void handleResult(ULocale locale, String result) throws ParseException {
    for (Iterator it = settings.keySet().iterator(); it.hasNext();) {
        String attributeName = (String) it.next();
        String attributeValue = (String) settings.get(attributeName);
        if (attributeName.equals("date")) {
            date = attributeValue;
        } else if (attributeName.equals("field")) {
            pattern = attributeValue;
        } else if (attributeName.equals("zone")) {
            zone = attributeValue;
        } else if (attributeName.equals("parse")) {
            parse = attributeValue;
        }
    }
    
    if (!ZONE_MATCH.reset(zone).matches()) return;
    Date dateValue = iso.parse(date);
    SimpleDateFormat field = new SimpleDateFormat(pattern, locale);
    field.setTimeZone(TimeZone.getTimeZone(zone));
    String temp = field.format(dateValue).trim();
    // SKIP PARSE FOR NOW
    result = result.trim(); // HACK because of SAX
    if (!temp.equals(result)) {
        temp = field.format(dateValue).trim(); // call again for debugging
        logln("Zone Format: Locale: " + locale 
                + "\n\tZone: " + zone
                + "\n\tDate: " + date
                + "\n\tField: " + pattern
                + "\n\tParse: " + parse
                + "\n\tDraft: " + settings.get("draft")
                + "\n\tCLDR: <" + result
                + ">\n\tICU: <" + temp + ">");
    }
}
 
Example #28
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 #29
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Calendar does not update field values when setTimeZone is called.
 */
@Test
public void Test4177484() {
    TimeZone PST = TimeZone.getTimeZone("PST");
    TimeZone EST = TimeZone.getTimeZone("EST");

    Calendar cal = Calendar.getInstance(PST, Locale.US);
    cal.clear();
    cal.set(1999, 3, 21, 15, 5, 0); // Arbitrary
    int h1 = cal.get(Calendar.HOUR_OF_DAY);
    cal.setTimeZone(EST);
    int h2 = cal.get(Calendar.HOUR_OF_DAY);
    if (h1 == h2) {
        errln("FAIL: Fields not updated after setTimeZone");
    }

    // getTime() must NOT change when time zone is changed.
    // getTime() returns zone-independent time in ms.
    cal.clear();
    cal.setTimeZone(PST);
    cal.set(Calendar.HOUR_OF_DAY, 10);
    Date pst10 = cal.getTime();
    cal.setTimeZone(EST);
    Date est10 = cal.getTime();
    if (!pst10.equals(est10)) {
        errln("FAIL: setTimeZone changed time");
    }
}
 
Example #30
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void Test4083167() {
    TimeZone saveZone = TimeZone.getDefault();
    try {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        Date firstDate = new Date();
        Calendar cal = new GregorianCalendar();
        cal.setTime(firstDate);
        long firstMillisInDay = cal.get(Calendar.HOUR_OF_DAY) * 3600000L +
            cal.get(Calendar.MINUTE) * 60000L +
            cal.get(Calendar.SECOND) * 1000L +
            cal.get(Calendar.MILLISECOND);
        
        logln("Current time: " + firstDate.toString());

        for (int validity=0; validity<30; validity++) {
            Date lastDate = new Date(firstDate.getTime() +
                                     (long)validity*1000*24*60*60);
            cal.setTime(lastDate);
            long millisInDay = cal.get(Calendar.HOUR_OF_DAY) * 3600000L +
                cal.get(Calendar.MINUTE) * 60000L +
                cal.get(Calendar.SECOND) * 1000L +
                cal.get(Calendar.MILLISECOND);
            if (firstMillisInDay != millisInDay) 
                errln("Day has shifted " + lastDate);
        }
    }
    finally {
        TimeZone.setDefault(saveZone);
    }
}