Java Code Examples for android.icu.text.SimpleDateFormat#setTimeZone()

The following examples show how to use android.icu.text.SimpleDateFormat#setTimeZone() . 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: TestMessageFormat.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestSetFormat() {
    MessageFormat ms = new MessageFormat("{number} {date}", ULocale.ENGLISH);
    final DecimalFormat decimalFormat = new DecimalFormat("000.000", DecimalFormatSymbols.getInstance(ULocale.ENGLISH));
    ms.setFormatByArgumentName("number", decimalFormat);
    final SimpleDateFormat dateFormat = new SimpleDateFormat("'year:'yy 'month:'MM 'day:'dd");
    dateFormat.setTimeZone(TimeZone.getTimeZone("Etc/GMT"));
    ms.setFormatByArgumentName("date", dateFormat);
    Map map = new HashMap();
    map.put("number", new Integer(1234));
    map.put("date", new Date(0,0,0));
    String result = ms.format(map);
    assertEquals("setFormatByArgumentName", "1234.000 year:99 month:12 day:31", result);
    Set formatNames = ms.getArgumentNames();
    assertEquals("Format Names match", formatNames, map.keySet());
    assertEquals("Decimal", decimalFormat, ms.getFormatByArgumentName("number"));
    assertEquals("Date", dateFormat, ms.getFormatByArgumentName("date"));
}
 
Example 2
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 3
Source File: CalendarRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test case for ticket 9452
 * Calendar addition fall onto the missing date - 2011-12-30 in Samoa
 */
@Test
public void TestT9452() {
    TimeZone samoaTZ = TimeZone.getTimeZone("Pacific/Apia");
    GregorianCalendar cal = new GregorianCalendar(samoaTZ);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
    sdf.setTimeZone(samoaTZ);

    // Set date to 2011-12-29 00:00
    cal.clear();
    cal.set(2011, Calendar.DECEMBER, 29, 0, 0, 0);

    Date d = cal.getTime();
    String dstr = sdf.format(d);
    logln("Initial date: " + dstr);

    // Add 1 day
    cal.add(Calendar.DATE, 1);
    d = cal.getTime();
    dstr = sdf.format(d);
    logln("+1 day: " + dstr);
    assertEquals("Add 1 day", "2011-12-31T00:00:00+14:00", dstr);

    // Subtract 1 day
    cal.add(Calendar.DATE, -1);
    d = cal.getTime();
    dstr = sdf.format(d);
    logln("-1 day: " + dstr);
    assertEquals("Subtract 1 day", "2011-12-29T00:00:00-10:00", dstr);
}
 
Example 4
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 5
Source File: DateFormatRegressionTestJ.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void run() {            
    SimpleDateFormat sdf = (SimpleDateFormat) sdf_.clone();
    TimeZone tz = TimeZone.getTimeZone("PST");
    sdf.setTimeZone(tz);
    int i = 0;
    while (i < 10000) {
        i++;
        String s = sdf.format(new Date(UTC_LONG));
        if (!s.equals(TIME_STRING)) {
            errln("Format Error: " + i + " " + s + " != " 
                            + TIME_STRING);
        }
    }
}
 
Example 6
Source File: DateTimeGeneratorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestRoot() {
    DateTimePatternGenerator rootGen = DateTimePatternGenerator.getInstance(ULocale.ROOT);
    SimpleDateFormat rootFormat = new SimpleDateFormat(rootGen.getBestPattern("yMdHms"), ULocale.ROOT);
    rootFormat.setTimeZone(gmt);
    // *** expected result should be "1999-10-14 6:58:59" with current data, changed test temporarily to match current result, needs investigation
    assertEquals("root format: yMdHms", "1999-10-14 06:58:59", rootFormat.format(sampleDate));
}
 
Example 7
Source File: DateTimeGeneratorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestEmpty() {
    // now nothing
    DateTimePatternGenerator nullGen = DateTimePatternGenerator.getEmptyInstance();
    SimpleDateFormat format = new SimpleDateFormat(nullGen.getBestPattern("yMdHms"), ULocale.ROOT);
    TimeZone rootZone = TimeZone.getTimeZone("Etc/GMT");
    format.setTimeZone(rootZone);
}
 
Example 8
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 9
Source File: GlobalizationPreferences.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Get the display name for an ID: language, script, territory, currency, timezone...
 * Uses the language priority list to do so.
 *
 * @param id language code, script code, ...
 * @param type specifies the type of the ID: ID_LANGUAGE, etc.
 * @return the display name
 * @hide draft / provisional / internal are hidden on Android
 */
public String getDisplayName(String id, int type) {
    String result = id;
    for (ULocale locale : getLocales()) {
        if (!isAvailableLocale(locale, TYPE_GENERIC)) {
            continue;
        }
        switch (type) {
        case ID_LOCALE:
            result = ULocale.getDisplayName(id, locale);
            break;
        case ID_LANGUAGE:
            result = ULocale.getDisplayLanguage(id, locale);
            break;
        case ID_SCRIPT:
            result = ULocale.getDisplayScript("und-" + id, locale);
            break;
        case ID_TERRITORY:
            result = ULocale.getDisplayCountry("und-" + id, locale);
            break;
        case ID_VARIANT:
            // TODO fix variant parsing
            result = ULocale.getDisplayVariant("und-QQ-" + id, locale);
            break;
        case ID_KEYWORD:
            result = ULocale.getDisplayKeyword(id, locale);
            break;
        case ID_KEYWORD_VALUE:
            String[] parts = new String[2];
            Utility.split(id,'=',parts);
            result = ULocale.getDisplayKeywordValue("und@"+id, parts[0], locale);
            // TODO fix to tell when successful
            if (result.equals(parts[1])) {
                continue;
            }
            break;
        case ID_CURRENCY_SYMBOL:
        case ID_CURRENCY:
            Currency temp = new Currency(id);
            result =temp.getName(locale, type==ID_CURRENCY
                                 ? Currency.LONG_NAME
                                 : Currency.SYMBOL_NAME, new boolean[1]);
            // TODO: have method that doesn't take parameter. Add
            // function to determine whether string is choice
            // format.
            // TODO: have method that doesn't require us
            // to create a currency
            break;
        case ID_TIMEZONE:
            SimpleDateFormat dtf = new SimpleDateFormat("vvvv",locale);
            dtf.setTimeZone(TimeZone.getFrozenTimeZone(id));
            result = dtf.format(new Date());
            // TODO, have method that doesn't require us to create a timezone
            // fix other hacks
            // hack for couldn't match

            boolean isBadStr = false;
            // Matcher badTimeZone = Pattern.compile("[A-Z]{2}|.*\\s\\([A-Z]{2}\\)").matcher("");
            // badtzstr = badTimeZone.reset(result).matches();
            String teststr = result;
            int sidx = result.indexOf('(');
            int eidx = result.indexOf(')');
            if (sidx != -1 && eidx != -1 && (eidx - sidx) == 3) {
                teststr = result.substring(sidx+1, eidx);
            }
            if (teststr.length() == 2) {
                isBadStr = true;
                for (int i = 0; i < 2; i++) {
                    char c = teststr.charAt(i);
                    if (c < 'A' || 'Z' < c) {
                        isBadStr = false;
                        break;
                    }
                }
            }
            if (isBadStr) {
                continue;
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown type: " + type);
        }

        // TODO need better way of seeing if we fell back to root!!
        // This will not work at all for lots of stuff
        if (!id.equals(result)) {
            return result;
        }
    }
    return result;
}
 
Example 10
Source File: TimeZoneRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * TimeZone broken at midnight.  The TimeZone code fails to handle
 * transitions at midnight correctly.
 */
@Test
public void Test4162593() {
    SimpleDateFormat fmt = new SimpleDateFormat("z", Locale.US);
    final int ONE_HOUR = 60*60*1000;
    final float H = (float) ONE_HOUR;
    TimeZone initialZone = TimeZone.getDefault();
    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm z");

    SimpleTimeZone asuncion = new SimpleTimeZone(-4*ONE_HOUR, "America/Asuncion" /*PY%sT*/,
        Calendar.OCTOBER, 1, 0 /*DOM*/, 0*ONE_HOUR,
        Calendar.MARCH, 1, 0 /*DOM*/, 0*ONE_HOUR, 1*ONE_HOUR);

    /* Zone
     * Starting time
     * Transition expected between start+1H and start+2H
     */
    Object[] DATA = {
        new SimpleTimeZone(2*ONE_HOUR, "Asia/Damascus" /*EE%sT*/,
            Calendar.APRIL, 1, 0 /*DOM*/, 0*ONE_HOUR,
            Calendar.OCTOBER, 1, 0 /*DOM*/, 0*ONE_HOUR, 1*ONE_HOUR),
        new int[] {1998, Calendar.SEPTEMBER, 30, 22, 0},
        Boolean.TRUE,

        asuncion,
        new int[] {2000, Calendar.FEBRUARY, 28, 22, 0},
        Boolean.FALSE,

        asuncion,
        new int[] {2000, Calendar.FEBRUARY, 29, 22, 0},
        Boolean.TRUE,
    };

    String[] zone = new String[4];

    for (int j=0; j<DATA.length; j+=3) {
        TimeZone tz = (TimeZone)DATA[j];
        TimeZone.setDefault(tz);
        fmt.setTimeZone(tz);
        sdf.setTimeZone(tz);

        // Must construct the Date object AFTER setting the default zone
        int[] p = (int[])DATA[j+1];
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(p[0], p[1], p[2], p[3], p[4]);
        long start = cal.getTime().getTime();
        boolean transitionExpected = ((Boolean)DATA[j+2]).booleanValue();

        logln(tz.getID() + ":");
        for (int i=0; i<4; ++i) {
            Date d = new Date(start + i*ONE_HOUR);
            zone[i] = fmt.format(d);
            logln("" + i + ": " + sdf.format(d) + " => " + zone[i] +
                  " (" + d.getTime()/H + ")");
        }
        cal.set(p[0], p[1], p[2], 0, 0);
        for (int i=0; i<4; ++i) {
            int h = 22+i;
            int dom = p[2]+(h>=24?1:0);
            h %= 24;
            int ms = h*ONE_HOUR;
            cal.clear();
            cal.set(p[0], p[1], dom, 0, 0);
            int off = tz.getOffset(GregorianCalendar.AD,
                                   cal.get(Calendar.YEAR),
                                   cal.get(Calendar.MONTH),
                                   cal.get(Calendar.DATE),
                                   cal.get(Calendar.DAY_OF_WEEK),
                                   ms);
            cal.add(Calendar.HOUR, h);
            int dstOffset = cal.get(Calendar.DST_OFFSET);
            logln("h=" + h + "; dom=" + dom +
                  "; ZONE_OFFSET=" + cal.get(Calendar.ZONE_OFFSET)/H +
                  "; DST_OFFSET=" + dstOffset/H +
                  "; getOffset()=" + off/H +
                  " (" + cal.getTime().getTime()/H + ")");
        }
        if (zone[0].equals(zone[1]) &&
            (zone[1].equals(zone[2]) != transitionExpected) &&
            zone[2].equals(zone[3])) {
            logln("Ok: transition " + transitionExpected);
        } else {
            errln("FAIL: expected " +
                  (transitionExpected?"transition":"no transition"));
        }
    }

// restore the initial time zone so that this test case
// doesn't affect the others.
TimeZone.setDefault(initialZone);
}
 
Example 11
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 12
Source File: DateFormatRegressionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * @bug 4106807
 */
@Test
public void Test4106807() {
    Date dt;
    DateFormat df = DateFormat.getDateTimeInstance();

    SimpleDateFormat sdfs[] = {
            new SimpleDateFormat("yyyyMMddHHmmss"), 
            new SimpleDateFormat("yyyyMMddHHmmss'Z'"), 
            new SimpleDateFormat("yyyyMMddHHmmss''"), 
            new SimpleDateFormat("yyyyMMddHHmmss'a''a'"), 
            new SimpleDateFormat("yyyyMMddHHmmss %")}; 
    String strings[] = {
            "19980211140000", 
            "19980211140000", 
            "19980211140000", 
            "19980211140000a", 
            "19980211140000 "}; 
    GregorianCalendar gc = new GregorianCalendar();
    TimeZone timeZone = TimeZone.getDefault();
    TimeZone gmt = (TimeZone) timeZone.clone();
    gmt.setRawOffset(0);
    for (int i = 0; i < 5; i++) {
        SimpleDateFormat format = sdfs[i];
        String dateString = strings[i];
        try {
            format.setTimeZone(gmt);
            dt = format.parse(dateString);
            // {sfb} some of these parses will fail purposely

            StringBuffer fmtd = new StringBuffer("");
            FieldPosition pos = new FieldPosition(0);
            fmtd = df.format(dt, fmtd, pos);
            logln(fmtd.toString());
            //logln(df.format(dt)); 
            gc.setTime(dt);
            logln("" + gc.get(Calendar.ZONE_OFFSET));
            StringBuffer s = new StringBuffer("");
            s = format.format(dt, s, pos);
            logln(s.toString());
        } catch (ParseException e) {
            logln("No way Jose");
        }
    }
}
 
Example 13
Source File: TestCLDRVsICU.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void handleResult(ULocale locale, String result) throws ParseException {
    int dateFormat = 0;
    int timeFormat = 0;
    Date date = new Date();
    boolean approved = true;

    for (Iterator it = settings.keySet().iterator(); it.hasNext();) {
        String attributeName = (String) it.next();
        String attributeValue = (String) settings.get(attributeName);

        // Checks if the attribute name is a draft and whether
        // or not it has been approved / contributed by CLDR yet
        // otherwise, skips it because it is most likely rejected by ICU
        if (attributeName.equals("draft")) {
            if (attributeValue.indexOf("approved") == -1 && attributeValue.indexOf("contributed") == -1) {
                approved = false;
                break;
            }
            continue;
        }

        // Update the value to be checked
        if (attributeName.equals("input")) {
            date = iso.parse(attributeValue);
            continue;
        }
        // At this point, it must be either dateType or timeType
        int index = lookupValue(attributeValue, DateFormatNames);
        if (attributeName.equals("dateType"))
            dateFormat = index;
        else if (attributeName.equals("timeType"))
            timeFormat = index;

    }

    // The attribute value must be approved in order to be checked,
    // if it hasn't been approved, it shouldn't be checked if it
    // matches with ICU
    if (approved) {
        SimpleDateFormat dt = getDateFormat(locale, dateFormat, timeFormat);
        dt.setTimeZone(utc);
        String temp = dt.format(date).trim();
        result = result.trim(); // HACK because of SAX
        if (!temp.equals(result)) {
            logln("DateTime: Locale: " + locale +
                    "\n\tDate: " + DateFormatNames[dateFormat] +
                    "\n\tTime: " + DateFormatNames[timeFormat] +
                    "\n\tDraft: " + settings.get("draft") +
                    "\n\tCLDR: <" + result + "> " +
                    "\n\tICU: <" + temp + ">");
        }
    }
}