Search in sources :

Example 1 with TimeType

use of android.icu.text.TimeZoneFormat.TimeType in project j2objc by google.

the class TimeZoneFormatTest method TestParse.

@Test
public void TestParse() {
    final Object[][] DATA = { // parseOptions            expected            outpos      time type
    { "Z", 0, "en_US", Style.ISO_EXTENDED_FULL, null, "Etc/GMT", 1, TimeType.UNKNOWN }, { "Z", 0, "en_US", Style.SPECIFIC_LONG, null, "Etc/GMT", 1, TimeType.UNKNOWN }, { "Zambia time", 0, "en_US", Style.ISO_EXTENDED_FULL, EnumSet.of(ParseOption.ALL_STYLES), "Etc/GMT", 1, TimeType.UNKNOWN }, { "Zambia time", 0, "en_US", Style.GENERIC_LOCATION, null, "Africa/Lusaka", 11, TimeType.UNKNOWN }, { "Zambia time", 0, "en_US", Style.ISO_BASIC_LOCAL_FULL, EnumSet.of(ParseOption.ALL_STYLES), "Africa/Lusaka", 11, TimeType.UNKNOWN }, { "+00:00", 0, "en_US", Style.ISO_EXTENDED_FULL, null, "Etc/GMT", 6, TimeType.UNKNOWN }, { "-01:30:45", 0, "en_US", Style.ISO_EXTENDED_FULL, null, "GMT-01:30:45", 9, TimeType.UNKNOWN }, { "-7", 0, "en_US", Style.ISO_BASIC_LOCAL_FULL, null, "GMT-07:00", 2, TimeType.UNKNOWN }, { "-2222", 0, "en_US", Style.ISO_BASIC_LOCAL_FULL, null, "GMT-22:22", 5, TimeType.UNKNOWN }, { "-3333", 0, "en_US", Style.ISO_BASIC_LOCAL_FULL, null, "GMT-03:33", 4, TimeType.UNKNOWN }, { "XXX+01:30YYY", 3, "en_US", Style.LOCALIZED_GMT, null, "GMT+01:30", 9, TimeType.UNKNOWN }, { "GMT0", 0, "en_US", Style.SPECIFIC_SHORT, null, "Etc/GMT", 3, TimeType.UNKNOWN }, { "EST", 0, "en_US", Style.SPECIFIC_SHORT, null, "America/New_York", 3, TimeType.STANDARD }, { "ESTx", 0, "en_US", Style.SPECIFIC_SHORT, null, "America/New_York", 3, TimeType.STANDARD }, { "EDTx", 0, "en_US", Style.SPECIFIC_SHORT, null, "America/New_York", 3, TimeType.DAYLIGHT }, { "EST", 0, "en_US", Style.SPECIFIC_LONG, null, null, 0, TimeType.UNKNOWN }, { "EST", 0, "en_US", Style.SPECIFIC_LONG, EnumSet.of(ParseOption.ALL_STYLES), "America/New_York", 3, TimeType.STANDARD }, { "EST", 0, "en_CA", Style.SPECIFIC_SHORT, null, "America/Toronto", 3, TimeType.STANDARD }, { "CST", 0, "en_US", Style.SPECIFIC_SHORT, null, "America/Chicago", 3, TimeType.STANDARD }, { "CST", 0, "en_GB", Style.SPECIFIC_SHORT, null, null, 0, TimeType.UNKNOWN }, { "CST", 0, "en_GB", Style.SPECIFIC_SHORT, EnumSet.of(ParseOption.TZ_DATABASE_ABBREVIATIONS), "America/Chicago", 3, TimeType.STANDARD }, { "--CST--", 2, "en_GB", Style.SPECIFIC_SHORT, EnumSet.of(ParseOption.TZ_DATABASE_ABBREVIATIONS), "America/Chicago", 5, TimeType.STANDARD }, { "CST", 0, "zh_CN", Style.SPECIFIC_SHORT, EnumSet.of(ParseOption.TZ_DATABASE_ABBREVIATIONS), "Asia/Shanghai", 3, TimeType.STANDARD }, { "AEST", 0, "en_AU", Style.SPECIFIC_SHORT, EnumSet.of(ParseOption.TZ_DATABASE_ABBREVIATIONS), "Australia/Sydney", 4, TimeType.STANDARD }, { "AST", 0, "ar_SA", Style.SPECIFIC_SHORT, EnumSet.of(ParseOption.TZ_DATABASE_ABBREVIATIONS), "Asia/Riyadh", 3, TimeType.STANDARD }, { "AQTST", 0, "en", Style.SPECIFIC_LONG, null, null, 0, TimeType.UNKNOWN }, { "AQTST", 0, "en", Style.SPECIFIC_LONG, EnumSet.of(ParseOption.ALL_STYLES), null, 0, TimeType.UNKNOWN }, { "AQTST", 0, "en", Style.SPECIFIC_LONG, EnumSet.of(ParseOption.ALL_STYLES, ParseOption.TZ_DATABASE_ABBREVIATIONS), "Asia/Aqtobe", 5, TimeType.DAYLIGHT }, { "hora de verano británica", 0, "es", Style.SPECIFIC_LONG, null, "Europe/London", 24, TimeType.DAYLIGHT } };
    for (Object[] test : DATA) {
        String text = (String) test[0];
        int inPos = (Integer) test[1];
        ULocale loc = new ULocale((String) test[2]);
        Style style = (Style) test[3];
        EnumSet<ParseOption> options = (EnumSet<ParseOption>) test[4];
        String expID = (String) test[5];
        int expPos = (Integer) test[6];
        TimeType expType = (TimeType) test[7];
        TimeZoneFormat tzfmt = TimeZoneFormat.getInstance(loc);
        Output<TimeType> timeType = new Output<TimeType>(TimeType.UNKNOWN);
        ParsePosition pos = new ParsePosition(inPos);
        TimeZone tz = tzfmt.parse(style, text, pos, options, timeType);
        String errMsg = null;
        if (tz == null) {
            if (expID != null) {
                errMsg = "Parse failure - expected: " + expID;
            }
        } else if (!tz.getID().equals(expID)) {
            errMsg = "Time zone ID: " + tz.getID() + " - expected: " + expID;
        } else if (pos.getIndex() != expPos) {
            errMsg = "Parsed pos: " + pos.getIndex() + " - expected: " + expPos;
        } else if (timeType.value != expType) {
            errMsg = "Time type: " + timeType + " - expected: " + expType;
        }
        if (errMsg != null) {
            errln("Fail: " + errMsg + " [text=" + text + ", pos=" + inPos + ", locale=" + loc + ", style=" + style + "]");
        }
    }
}
Also used : ULocale(android.icu.util.ULocale) EnumSet(java.util.EnumSet) TimeZoneFormat(android.icu.text.TimeZoneFormat) TimeType(android.icu.text.TimeZoneFormat.TimeType) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SimpleTimeZone(android.icu.util.SimpleTimeZone) TimeZone(android.icu.util.TimeZone) BasicTimeZone(android.icu.util.BasicTimeZone) Output(android.icu.util.Output) Style(android.icu.text.TimeZoneFormat.Style) ParseOption(android.icu.text.TimeZoneFormat.ParseOption) ParsePosition(java.text.ParsePosition) Test(org.junit.Test)

Example 2 with TimeType

use of android.icu.text.TimeZoneFormat.TimeType in project j2objc by google.

the class SimpleDateFormat method parse.

/**
 * Overrides DateFormat
 * @see DateFormat
 */
@Override
public void parse(String text, Calendar cal, ParsePosition parsePos) {
    TimeZone backupTZ = null;
    Calendar resultCal = null;
    if (cal != calendar && !cal.getType().equals(calendar.getType())) {
        // Different calendar type
        // We use the 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());
        resultCal = cal;
        cal = calendar;
    }
    int pos = parsePos.getIndex();
    if (pos < 0) {
        parsePos.setErrorIndex(0);
        return;
    }
    int start = pos;
    // Hold the day period until everything else is parsed, because we need
    // the hour to interpret time correctly.
    // Using an one-element array for output parameter.
    Output<DayPeriodRules.DayPeriod> dayPeriod = new Output<DayPeriodRules.DayPeriod>(null);
    Output<TimeType> tzTimeType = new Output<TimeType>(TimeType.UNKNOWN);
    boolean[] ambiguousYear = { false };
    // item index for the first numeric field within a contiguous numeric run
    int numericFieldStart = -1;
    // item length for the first numeric field within a contiguous numeric run
    int numericFieldLength = 0;
    // start index of numeric text run in the input text
    int numericStartPos = 0;
    MessageFormat numericLeapMonthFormatter = null;
    if (formatData.leapMonthPatterns != null && formatData.leapMonthPatterns.length >= DateFormatSymbols.DT_MONTH_PATTERN_COUNT) {
        numericLeapMonthFormatter = new MessageFormat(formatData.leapMonthPatterns[DateFormatSymbols.DT_LEAP_MONTH_PATTERN_NUMERIC], locale);
    }
    Object[] items = getPatternItems();
    int i = 0;
    while (i < items.length) {
        if (items[i] instanceof PatternItem) {
            // Handle pattern field
            PatternItem field = (PatternItem) items[i];
            if (field.isNumeric) {
                // try 4/2/2, 3/2/2, 2/2/2, and finally 1/2/2.
                if (numericFieldStart == -1) {
                    // check if this field is followed by abutting another numeric field
                    if ((i + 1) < items.length && (items[i + 1] instanceof PatternItem) && ((PatternItem) items[i + 1]).isNumeric) {
                        // record the first numeric field within a numeric text run
                        numericFieldStart = i;
                        numericFieldLength = field.length;
                        numericStartPos = pos;
                    }
                }
            }
            if (numericFieldStart != -1) {
                // Handle a numeric field within abutting numeric fields
                int len = field.length;
                if (numericFieldStart == i) {
                    len = numericFieldLength;
                }
                // Parse a numeric field
                pos = subParse(text, pos, field.type, len, true, false, ambiguousYear, cal, numericLeapMonthFormatter, tzTimeType);
                if (pos < 0) {
                    // If the parse fails anywhere in the numeric run, back up to the
                    // start of the run and use shorter pattern length for the first
                    // numeric field.
                    --numericFieldLength;
                    if (numericFieldLength == 0) {
                        // can not make shorter any more
                        parsePos.setIndex(start);
                        parsePos.setErrorIndex(pos);
                        if (backupTZ != null) {
                            calendar.setTimeZone(backupTZ);
                        }
                        return;
                    }
                    i = numericFieldStart;
                    pos = numericStartPos;
                    continue;
                }
            } else if (field.type != 'l') {
                // (SMALL LETTER L) obsolete pattern char just gets ignored
                // Handle a non-numeric field or a non-abutting numeric field
                numericFieldStart = -1;
                int s = pos;
                pos = subParse(text, pos, field.type, field.length, false, true, ambiguousYear, cal, numericLeapMonthFormatter, tzTimeType, dayPeriod);
                if (pos < 0) {
                    if (pos == ISOSpecialEra) {
                        // era not present, in special cases allow this to continue
                        pos = s;
                        if (i + 1 < items.length) {
                            String patl = null;
                            // if it will cause a class cast exception to String, we can't use it
                            try {
                                patl = (String) items[i + 1];
                            } catch (ClassCastException cce) {
                                parsePos.setIndex(start);
                                parsePos.setErrorIndex(s);
                                if (backupTZ != null) {
                                    calendar.setTimeZone(backupTZ);
                                }
                                return;
                            }
                            // get next item in pattern
                            if (patl == null)
                                patl = (String) items[i + 1];
                            int plen = patl.length();
                            int idx = 0;
                            // Skip contiguous white spaces.
                            while (idx < plen) {
                                char pch = patl.charAt(idx);
                                if (PatternProps.isWhiteSpace(pch))
                                    idx++;
                                else
                                    break;
                            }
                            // if next item in pattern is all whitespace, skip it
                            if (idx == plen) {
                                i++;
                            }
                        }
                    } else {
                        parsePos.setIndex(start);
                        parsePos.setErrorIndex(s);
                        if (backupTZ != null) {
                            calendar.setTimeZone(backupTZ);
                        }
                        return;
                    }
                }
            }
        } else {
            // Handle literal pattern text literal
            numericFieldStart = -1;
            boolean[] complete = new boolean[1];
            pos = matchLiteral(text, pos, items, i, complete);
            if (!complete[0]) {
                // Set the position of mismatch
                parsePos.setIndex(start);
                parsePos.setErrorIndex(pos);
                if (backupTZ != null) {
                    calendar.setTimeZone(backupTZ);
                }
                return;
            }
        }
        ++i;
    }
    // Special hack for trailing "." after non-numeric field.
    if (pos < text.length()) {
        char extra = text.charAt(pos);
        if (extra == '.' && getBooleanAttribute(DateFormat.BooleanAttribute.PARSE_ALLOW_WHITESPACE) && items.length != 0) {
            // only do if the last field is not numeric
            Object lastItem = items[items.length - 1];
            if (lastItem instanceof PatternItem && !((PatternItem) lastItem).isNumeric) {
                // skip the extra "."
                pos++;
            }
        }
    }
    // If dayPeriod is set, use it in conjunction with hour-of-day to determine am/pm.
    if (dayPeriod.value != null) {
        DayPeriodRules ruleSet = DayPeriodRules.getInstance(getLocale());
        if (!cal.isSet(Calendar.HOUR) && !cal.isSet(Calendar.HOUR_OF_DAY)) {
            // If hour is not set, set time to the midpoint of current day period, overwriting
            // minutes if it's set.
            double midPoint = ruleSet.getMidPointForDayPeriod(dayPeriod.value);
            // Truncate midPoint toward zero to get the hour.
            // Any leftover means it was a half-hour.
            int midPointHour = (int) midPoint;
            int midPointMinute = (midPoint - midPointHour) > 0 ? 30 : 0;
            // No need to set am/pm because hour-of-day is set last therefore takes precedence.
            cal.set(Calendar.HOUR_OF_DAY, midPointHour);
            cal.set(Calendar.MINUTE, midPointMinute);
        } else {
            int hourOfDay;
            if (cal.isSet(Calendar.HOUR_OF_DAY)) {
                // Hour is parsed in 24-hour format.
                hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
            } else {
                // Hour is parsed in 12-hour format.
                hourOfDay = cal.get(Calendar.HOUR);
                // so 0 unambiguously means a 24-hour time from above.
                if (hourOfDay == 0) {
                    hourOfDay = 12;
                }
            }
            assert (0 <= hourOfDay && hourOfDay <= 23);
            // If hour-of-day is 0 or 13 thru 23 then input time in unambiguously in 24-hour format.
            if (hourOfDay == 0 || (13 <= hourOfDay && hourOfDay <= 23)) {
                // Make hour-of-day take precedence over (hour + am/pm) by setting it again.
                cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
            } else {
                // - cal.get(MINUTE) will return 0 if MINUTE is unset, which works.
                if (hourOfDay == 12) {
                    hourOfDay = 0;
                }
                double currentHour = hourOfDay + cal.get(Calendar.MINUTE) / 60.0;
                double midPointHour = ruleSet.getMidPointForDayPeriod(dayPeriod.value);
                double hoursAheadMidPoint = currentHour - midPointHour;
                // Assume current time is in the AM.
                if (-6 <= hoursAheadMidPoint && hoursAheadMidPoint < 6) {
                    // Assumption holds; set time as such.
                    cal.set(Calendar.AM_PM, 0);
                } else {
                    cal.set(Calendar.AM_PM, 1);
                }
            }
        }
    }
    // At this point the fields of Calendar have been set.  Calendar
    // will fill in default values for missing fields when the time
    // is computed.
    parsePos.setIndex(pos);
    // the year correctly to start with in other cases -- see subParse().
    try {
        TimeType tztype = tzTimeType.value;
        if (ambiguousYear[0] || tztype != TimeType.UNKNOWN) {
            // We need a copy of the fields, and we need to avoid triggering a call to
            // complete(), which will recalculate the fields.  Since we can't access
            // the fields[] array in Calendar, we clone the entire object.  This will
            // stop working if Calendar.clone() is ever rewritten to call complete().
            Calendar copy;
            if (ambiguousYear[0]) {
                // the two-digit year == the default start year
                copy = (Calendar) cal.clone();
                Date parsedDate = copy.getTime();
                if (parsedDate.before(getDefaultCenturyStart())) {
                    // We can't use add here because that does a complete() first.
                    cal.set(Calendar.YEAR, getDefaultCenturyStartYear() + 100);
                }
            }
            if (tztype != TimeType.UNKNOWN) {
                copy = (Calendar) cal.clone();
                TimeZone tz = copy.getTimeZone();
                BasicTimeZone btz = null;
                if (tz instanceof BasicTimeZone) {
                    btz = (BasicTimeZone) tz;
                }
                // Get local millis
                copy.set(Calendar.ZONE_OFFSET, 0);
                copy.set(Calendar.DST_OFFSET, 0);
                long localMillis = copy.getTimeInMillis();
                // Make sure parsed time zone type (Standard or Daylight)
                // matches the rule used by the parsed time zone.
                int[] offsets = new int[2];
                if (btz != null) {
                    if (tztype == TimeType.STANDARD) {
                        btz.getOffsetFromLocal(localMillis, BasicTimeZone.LOCAL_STD, BasicTimeZone.LOCAL_STD, offsets);
                    } else {
                        btz.getOffsetFromLocal(localMillis, BasicTimeZone.LOCAL_DST, BasicTimeZone.LOCAL_DST, offsets);
                    }
                } else {
                    // No good way to resolve ambiguous time at transition,
                    // but following code work in most case.
                    tz.getOffset(localMillis, true, offsets);
                    if (tztype == TimeType.STANDARD && offsets[1] != 0 || tztype == TimeType.DAYLIGHT && offsets[1] == 0) {
                        // Roll back one day and try it again.
                        // Note: This code assumes 1. timezone transition only happens
                        // once within 24 hours at max
                        // 2. the difference of local offsets at the transition is
                        // less than 24 hours.
                        tz.getOffset(localMillis - (24 * 60 * 60 * 1000), true, offsets);
                    }
                }
                // Now, compare the results with parsed type, either standard or
                // daylight saving time
                int resolvedSavings = offsets[1];
                if (tztype == TimeType.STANDARD) {
                    if (offsets[1] != 0) {
                        // Override DST_OFFSET = 0 in the result calendar
                        resolvedSavings = 0;
                    }
                } else {
                    // tztype == TZTYPE_DST
                    if (offsets[1] == 0) {
                        if (btz != null) {
                            long time = localMillis + offsets[0];
                            // We use the nearest daylight saving time rule.
                            TimeZoneTransition beforeTrs, afterTrs;
                            long beforeT = time, afterT = time;
                            int beforeSav = 0, afterSav = 0;
                            // Search for DST rule before or on the time
                            while (true) {
                                beforeTrs = btz.getPreviousTransition(beforeT, true);
                                if (beforeTrs == null) {
                                    break;
                                }
                                beforeT = beforeTrs.getTime() - 1;
                                beforeSav = beforeTrs.getFrom().getDSTSavings();
                                if (beforeSav != 0) {
                                    break;
                                }
                            }
                            // Search for DST rule after the time
                            while (true) {
                                afterTrs = btz.getNextTransition(afterT, false);
                                if (afterTrs == null) {
                                    break;
                                }
                                afterT = afterTrs.getTime();
                                afterSav = afterTrs.getTo().getDSTSavings();
                                if (afterSav != 0) {
                                    break;
                                }
                            }
                            if (beforeTrs != null && afterTrs != null) {
                                if (time - beforeT > afterT - time) {
                                    resolvedSavings = afterSav;
                                } else {
                                    resolvedSavings = beforeSav;
                                }
                            } else if (beforeTrs != null && beforeSav != 0) {
                                resolvedSavings = beforeSav;
                            } else if (afterTrs != null && afterSav != 0) {
                                resolvedSavings = afterSav;
                            } else {
                                resolvedSavings = btz.getDSTSavings();
                            }
                        } else {
                            resolvedSavings = tz.getDSTSavings();
                        }
                        if (resolvedSavings == 0) {
                            // Final fallback
                            resolvedSavings = millisPerHour;
                        }
                    }
                }
                cal.set(Calendar.ZONE_OFFSET, offsets[0]);
                cal.set(Calendar.DST_OFFSET, resolvedSavings);
            }
        }
    }// if any fields are out of range, e.g., MONTH == 17.
     catch (IllegalArgumentException e) {
        parsePos.setErrorIndex(pos);
        parsePos.setIndex(start);
        if (backupTZ != null) {
            calendar.setTimeZone(backupTZ);
        }
        return;
    }
    // instead of the input calendar
    if (resultCal != null) {
        resultCal.setTimeZone(cal.getTimeZone());
        resultCal.setTimeInMillis(cal.getTimeInMillis());
    }
    // Restore the original time zone if required
    if (backupTZ != null) {
        calendar.setTimeZone(backupTZ);
    }
}
Also used : DayPeriodRules(android.icu.impl.DayPeriodRules) HebrewCalendar(android.icu.util.HebrewCalendar) Calendar(android.icu.util.Calendar) AttributedString(java.text.AttributedString) Date(java.util.Date) TimeType(android.icu.text.TimeZoneFormat.TimeType) TimeZone(android.icu.util.TimeZone) BasicTimeZone(android.icu.util.BasicTimeZone) BasicTimeZone(android.icu.util.BasicTimeZone) TimeZoneTransition(android.icu.util.TimeZoneTransition) Output(android.icu.util.Output)

Example 3 with TimeType

use of android.icu.text.TimeZoneFormat.TimeType in project j2objc by google.

the class TimeZoneGenericNames method createGenericMatchInfo.

/**
 * Returns a <code>GenericMatchInfo</code> for the given <code>MatchInfo</code>.
 * @param matchInfo the MatchInfo
 * @return A GenericMatchInfo
 */
private GenericMatchInfo createGenericMatchInfo(MatchInfo matchInfo) {
    GenericNameType nameType = null;
    TimeType timeType = TimeType.UNKNOWN;
    switch(matchInfo.nameType()) {
        case LONG_STANDARD:
            nameType = GenericNameType.LONG;
            timeType = TimeType.STANDARD;
            break;
        case LONG_GENERIC:
            nameType = GenericNameType.LONG;
            break;
        case SHORT_STANDARD:
            nameType = GenericNameType.SHORT;
            timeType = TimeType.STANDARD;
            break;
        case SHORT_GENERIC:
            nameType = GenericNameType.SHORT;
            break;
        default:
            throw new IllegalArgumentException("Unexpected MatchInfo name type - " + matchInfo.nameType());
    }
    String tzID = matchInfo.tzID();
    if (tzID == null) {
        String mzID = matchInfo.mzID();
        assert (mzID != null);
        tzID = _tznames.getReferenceZoneID(mzID, getTargetRegion());
    }
    assert (tzID != null);
    GenericMatchInfo gmatch = new GenericMatchInfo(nameType, tzID, matchInfo.matchLength(), timeType);
    return gmatch;
}
Also used : TimeType(android.icu.text.TimeZoneFormat.TimeType)

Example 4 with TimeType

use of android.icu.text.TimeZoneFormat.TimeType in project j2objc by google.

the class TimeZone method _getDisplayName.

/**
 * internal version (which is called by public APIs) accepts
 * SHORT, LONG, SHORT_GENERIC, LONG_GENERIC, SHORT_GMT, LONG_GMT,
 * SHORT_COMMONLY_USED and GENERIC_LOCATION.
 */
private String _getDisplayName(int style, boolean daylight, ULocale locale) {
    if (locale == null) {
        throw new NullPointerException("locale is null");
    }
    String result = null;
    if (style == GENERIC_LOCATION || style == LONG_GENERIC || style == SHORT_GENERIC) {
        // Generic format
        TimeZoneFormat tzfmt = TimeZoneFormat.getInstance(locale);
        long date = System.currentTimeMillis();
        Output<TimeType> timeType = new Output<TimeType>(TimeType.UNKNOWN);
        switch(style) {
            case GENERIC_LOCATION:
                result = tzfmt.format(Style.GENERIC_LOCATION, this, date, timeType);
                break;
            case LONG_GENERIC:
                result = tzfmt.format(Style.GENERIC_LONG, this, date, timeType);
                break;
            case SHORT_GENERIC:
                result = tzfmt.format(Style.GENERIC_SHORT, this, date, timeType);
                break;
        }
        // appropriate for the requested daylight value.
        if (daylight && timeType.value == TimeType.STANDARD || !daylight && timeType.value == TimeType.DAYLIGHT) {
            int offset = daylight ? getRawOffset() + getDSTSavings() : getRawOffset();
            result = (style == SHORT_GENERIC) ? tzfmt.formatOffsetShortLocalizedGMT(offset) : tzfmt.formatOffsetLocalizedGMT(offset);
        }
    } else if (style == LONG_GMT || style == SHORT_GMT) {
        // Offset format
        TimeZoneFormat tzfmt = TimeZoneFormat.getInstance(locale);
        int offset = daylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
        switch(style) {
            case LONG_GMT:
                result = tzfmt.formatOffsetLocalizedGMT(offset);
                break;
            case SHORT_GMT:
                result = tzfmt.formatOffsetISO8601Basic(offset, false, false, false);
                break;
        }
    } else {
        // Specific format
        assert (style == LONG || style == SHORT || style == SHORT_COMMONLY_USED);
        // Gets the name directly from TimeZoneNames
        long date = System.currentTimeMillis();
        TimeZoneNames tznames = TimeZoneNames.getInstance(locale);
        NameType nameType = null;
        switch(style) {
            case LONG:
                nameType = daylight ? NameType.LONG_DAYLIGHT : NameType.LONG_STANDARD;
                break;
            case SHORT:
            case SHORT_COMMONLY_USED:
                nameType = daylight ? NameType.SHORT_DAYLIGHT : NameType.SHORT_STANDARD;
                break;
        }
        result = tznames.getDisplayName(ZoneMeta.getCanonicalCLDRID(this), nameType, date);
        if (result == null) {
            // Fallback to localized GMT
            TimeZoneFormat tzfmt = TimeZoneFormat.getInstance(locale);
            int offset = daylight && useDaylightTime() ? getRawOffset() + getDSTSavings() : getRawOffset();
            result = (style == LONG) ? tzfmt.formatOffsetLocalizedGMT(offset) : tzfmt.formatOffsetShortLocalizedGMT(offset);
        }
    }
    assert (result != null);
    return result;
}
Also used : TimeZoneNames(android.icu.text.TimeZoneNames) NameType(android.icu.text.TimeZoneNames.NameType) TimeZoneFormat(android.icu.text.TimeZoneFormat) TimeType(android.icu.text.TimeZoneFormat.TimeType)

Example 5 with TimeType

use of android.icu.text.TimeZoneFormat.TimeType in project j2objc by google.

the class TimeZoneFormatTest method TestFormat.

@Test
public void TestFormat() {
    // 2013-01-15T00:00:00Z
    final Date dateJan = new Date(1358208000000L);
    // 2013-07-15T00:00:00Z
    final Date dateJul = new Date(1373846400000L);
    final Object[][] TESTDATA = { { "en", "America/Los_Angeles", dateJan, Style.GENERIC_LOCATION, "Los Angeles Time", TimeType.UNKNOWN }, { "en", "America/Los_Angeles", dateJan, Style.GENERIC_LONG, "Pacific Time", TimeType.UNKNOWN }, { "en", "America/Los_Angeles", dateJan, Style.SPECIFIC_LONG, "Pacific Standard Time", TimeType.STANDARD }, { "en", "America/Los_Angeles", dateJul, Style.SPECIFIC_LONG, "Pacific Daylight Time", TimeType.DAYLIGHT }, { "ja", "America/Los_Angeles", dateJan, Style.ZONE_ID, "America/Los_Angeles", TimeType.UNKNOWN }, { "fr", "America/Los_Angeles", dateJul, Style.ZONE_ID_SHORT, "uslax", TimeType.UNKNOWN }, { "en", "America/Los_Angeles", dateJan, Style.EXEMPLAR_LOCATION, "Los Angeles", TimeType.UNKNOWN }, { "ja", "Asia/Tokyo", dateJan, Style.GENERIC_LONG, // "日本標準時"
    "\u65E5\u672C\u6A19\u6E96\u6642", TimeType.UNKNOWN } };
    for (Object[] testCase : TESTDATA) {
        TimeZone tz = TimeZone.getTimeZone((String) testCase[1]);
        Output<TimeType> timeType = new Output<TimeType>();
        ULocale uloc = new ULocale((String) testCase[0]);
        TimeZoneFormat tzfmt = TimeZoneFormat.getInstance(uloc);
        String out = tzfmt.format((Style) testCase[3], tz, ((Date) testCase[2]).getTime(), timeType);
        if (!out.equals(testCase[4]) || timeType.value != testCase[5]) {
            errln("Format result for [locale=" + testCase[0] + ",tzid=" + testCase[1] + ",date=" + testCase[2] + ",style=" + testCase[3] + "]: expected [output=" + testCase[4] + ",type=" + testCase[5] + "]; actual [output=" + out + ",type=" + timeType.value + "]");
        }
        // with equivalent Java Locale
        Locale loc = uloc.toLocale();
        tzfmt = TimeZoneFormat.getInstance(loc);
        out = tzfmt.format((Style) testCase[3], tz, ((Date) testCase[2]).getTime(), timeType);
        if (!out.equals(testCase[4]) || timeType.value != testCase[5]) {
            errln("Format result for [locale(Java)=" + testCase[0] + ",tzid=" + testCase[1] + ",date=" + testCase[2] + ",style=" + testCase[3] + "]: expected [output=" + testCase[4] + ",type=" + testCase[5] + "]; actual [output=" + out + ",type=" + timeType.value + "]");
        }
    }
}
Also used : Locale(java.util.Locale) ULocale(android.icu.util.ULocale) ULocale(android.icu.util.ULocale) TimeZoneFormat(android.icu.text.TimeZoneFormat) Date(java.util.Date) TimeType(android.icu.text.TimeZoneFormat.TimeType) SimpleTimeZone(android.icu.util.SimpleTimeZone) TimeZone(android.icu.util.TimeZone) BasicTimeZone(android.icu.util.BasicTimeZone) Output(android.icu.util.Output) Style(android.icu.text.TimeZoneFormat.Style) Test(org.junit.Test)

Aggregations

TimeType (android.icu.text.TimeZoneFormat.TimeType)6 TimeZoneFormat (android.icu.text.TimeZoneFormat)4 BasicTimeZone (android.icu.util.BasicTimeZone)4 Output (android.icu.util.Output)4 TimeZone (android.icu.util.TimeZone)4 SimpleTimeZone (android.icu.util.SimpleTimeZone)3 ULocale (android.icu.util.ULocale)3 Date (java.util.Date)3 Test (org.junit.Test)3 Style (android.icu.text.TimeZoneFormat.Style)2 TimeZoneNames (android.icu.text.TimeZoneNames)2 DayPeriodRules (android.icu.impl.DayPeriodRules)1 TZDBTimeZoneNames (android.icu.impl.TZDBTimeZoneNames)1 ParseOption (android.icu.text.TimeZoneFormat.ParseOption)1 NameType (android.icu.text.TimeZoneNames.NameType)1 Calendar (android.icu.util.Calendar)1 HebrewCalendar (android.icu.util.HebrewCalendar)1 TimeZoneTransition (android.icu.util.TimeZoneTransition)1 AttributedString (java.text.AttributedString)1 ParsePosition (java.text.ParsePosition)1