use of android.icu.util.BasicTimeZone in project android_packages_apps_Settings by omnirom.
the class TimeZoneInfoPreferenceController method findNextDstTransition.
private TimeZoneTransition findNextDstTransition(TimeZone timeZone) {
if (!(timeZone instanceof BasicTimeZone)) {
return null;
}
final BasicTimeZone basicTimeZone = (BasicTimeZone) timeZone;
TimeZoneTransition transition = basicTimeZone.getNextTransition(mDate.getTime(), /* inclusive */
false);
do {
if (transition.getTo().getDSTSavings() != transition.getFrom().getDSTSavings()) {
break;
}
transition = basicTimeZone.getNextTransition(transition.getTime(), /*inclusive */
false);
} while (transition != null);
return transition;
}
use of android.icu.util.BasicTimeZone 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);
}
}
use of android.icu.util.BasicTimeZone in project j2objc by google.
the class TimeZoneGenericNames method formatGenericNonLocationName.
/**
* Private method to get a generic string, with fallback logics involved,
* that is,
*
* 1. If a generic non-location string is available for the zone, return it.
* 2. If a generic non-location string is associated with a meta zone and
* the zone never use daylight time around the given date, use the standard
* string (if available).
* 3. If a generic non-location string is associated with a meta zone and
* the offset at the given time is different from the preferred zone for the
* current locale, then return the generic partial location string (if available)
* 4. If a generic non-location string is not available, use generic location
* string.
*
* @param tz the requested time zone
* @param date the date
* @param type the generic name type, either LONG or SHORT
* @return the name used for a generic name type, which could be the
* generic name, or the standard name (if the zone does not observes DST
* around the date), or the partial location name.
*/
private String formatGenericNonLocationName(TimeZone tz, GenericNameType type, long date) {
assert (type == GenericNameType.LONG || type == GenericNameType.SHORT);
String tzID = ZoneMeta.getCanonicalCLDRID(tz);
if (tzID == null) {
return null;
}
// Try to get a name from time zone first
NameType nameType = (type == GenericNameType.LONG) ? NameType.LONG_GENERIC : NameType.SHORT_GENERIC;
String name = _tznames.getTimeZoneDisplayName(tzID, nameType);
if (name != null) {
return name;
}
// Try meta zone
String mzID = _tznames.getMetaZoneID(tzID, date);
if (mzID != null) {
boolean useStandard = false;
int[] offsets = { 0, 0 };
tz.getOffset(date, false, offsets);
if (offsets[1] == 0) {
useStandard = true;
// Check if the zone actually uses daylight saving time around the time
if (tz instanceof BasicTimeZone) {
BasicTimeZone btz = (BasicTimeZone) tz;
TimeZoneTransition before = btz.getPreviousTransition(date, true);
if (before != null && (date - before.getTime() < DST_CHECK_RANGE) && before.getFrom().getDSTSavings() != 0) {
useStandard = false;
} else {
TimeZoneTransition after = btz.getNextTransition(date, false);
if (after != null && (after.getTime() - date < DST_CHECK_RANGE) && after.getTo().getDSTSavings() != 0) {
useStandard = false;
}
}
} else {
// If not BasicTimeZone... only if the instance is not an ICU's implementation.
// We may get a wrong answer in edge case, but it should practically work OK.
int[] tmpOffsets = new int[2];
tz.getOffset(date - DST_CHECK_RANGE, false, tmpOffsets);
if (tmpOffsets[1] != 0) {
useStandard = false;
} else {
tz.getOffset(date + DST_CHECK_RANGE, false, tmpOffsets);
if (tmpOffsets[1] != 0) {
useStandard = false;
}
}
}
}
if (useStandard) {
NameType stdNameType = (nameType == NameType.LONG_GENERIC) ? NameType.LONG_STANDARD : NameType.SHORT_STANDARD;
String stdName = _tznames.getDisplayName(tzID, stdNameType, date);
if (stdName != null) {
name = stdName;
// TODO: revisit this issue later
// In CLDR, a same display name is used for both generic and standard
// for some meta zones in some locales. This looks like a data bugs.
// For now, we check if the standard name is different from its generic
// name below.
String mzGenericName = _tznames.getMetaZoneDisplayName(mzID, nameType);
if (stdName.equalsIgnoreCase(mzGenericName)) {
name = null;
}
}
}
if (name == null) {
// Get a name from meta zone
String mzName = _tznames.getMetaZoneDisplayName(mzID, nameType);
if (mzName != null) {
// Check if we need to use a partial location format.
// This check is done by comparing offset with the meta zone's
// golden zone at the given date.
String goldenID = _tznames.getReferenceZoneID(mzID, getTargetRegion());
if (goldenID != null && !goldenID.equals(tzID)) {
TimeZone goldenZone = TimeZone.getFrozenTimeZone(goldenID);
int[] offsets1 = { 0, 0 };
// Check offset in the golden zone with wall time.
// With getOffset(date, false, offsets1),
// you may get incorrect results because of time overlap at DST->STD
// transition.
goldenZone.getOffset(date + offsets[0] + offsets[1], true, offsets1);
if (offsets[0] != offsets1[0] || offsets[1] != offsets1[1]) {
// Now we need to use a partial location format.
name = getPartialLocationName(tzID, mzID, (nameType == NameType.LONG_GENERIC), mzName);
} else {
name = mzName;
}
} else {
name = mzName;
}
}
}
}
return name;
}
use of android.icu.util.BasicTimeZone in project j2objc by google.
the class TimeZoneRuleTest method TestVTimeZoneCoverage.
/*
* API coverage test for VTimeZone
*/
@Test
public void TestVTimeZoneCoverage() {
final String TZID = "Europe/Moscow";
BasicTimeZone otz = (BasicTimeZone) TimeZone.getTimeZone(TZID, TimeZone.TIMEZONE_ICU);
VTimeZone vtz = VTimeZone.create(TZID);
// getOffset(era, year, month, day, dayOfWeek, milliseconds)
int offset1 = otz.getOffset(GregorianCalendar.AD, 2007, Calendar.JULY, 1, Calendar.SUNDAY, 0);
int offset2 = vtz.getOffset(GregorianCalendar.AD, 2007, Calendar.JULY, 1, Calendar.SUNDAY, 0);
if (offset1 != offset2) {
errln("FAIL: getOffset(int,int,int,int,int,int) returned different results in VTimeZone and OlsonTimeZone");
}
// getOffset(date, local, offsets)
int[] offsets1 = new int[2];
int[] offsets2 = new int[2];
long t = System.currentTimeMillis();
otz.getOffset(t, false, offsets1);
vtz.getOffset(t, false, offsets2);
if (offsets1[0] != offsets2[0] || offsets1[1] != offsets2[1]) {
errln("FAIL: getOffset(long,boolean,int[]) returned different results in VTimeZone and OlsonTimeZone");
}
// getRawOffset
if (otz.getRawOffset() != vtz.getRawOffset()) {
errln("FAIL: getRawOffset returned different results in VTimeZone and OlsonTimeZone");
}
// inDaylightTime
Date d = new Date();
if (otz.inDaylightTime(d) != vtz.inDaylightTime(d)) {
errln("FAIL: inDaylightTime returned different results in VTimeZone and OlsonTimeZone");
}
// useDaylightTime
if (otz.useDaylightTime() != vtz.useDaylightTime()) {
errln("FAIL: useDaylightTime returned different results in VTimeZone and OlsonTimeZone");
}
// setRawOffset
final int RAW = -10 * HOUR;
VTimeZone tmpvtz = (VTimeZone) vtz.clone();
tmpvtz.setRawOffset(RAW);
if (tmpvtz.getRawOffset() != RAW) {
logln("setRawOffset is implemented");
}
// hasSameRules
boolean bSame = otz.hasSameRules(vtz);
logln("OlsonTimeZone#hasSameRules(VTimeZone) should return false always for now - actual: " + bSame);
// getTZURL/setTZURL
final String TZURL = "http://icu-project.org/timezone";
String tzurl = vtz.getTZURL();
if (tzurl != null) {
errln("FAIL: getTZURL returned non-null value");
}
vtz.setTZURL(TZURL);
tzurl = vtz.getTZURL();
if (!TZURL.equals(tzurl)) {
errln("FAIL: URL returned by getTZURL does not match the one set by setTZURL");
}
// getLastModified/setLastModified
Date lastmod = vtz.getLastModified();
if (lastmod != null) {
errln("FAIL: getLastModified returned non-null value");
}
Date newdate = new Date();
vtz.setLastModified(newdate);
lastmod = vtz.getLastModified();
if (!newdate.equals(lastmod)) {
errln("FAIL: Date returned by getLastModified does not match the one set by setLastModified");
}
// getNextTransition/getPreviousTransition
long base = getUTCMillis(2007, Calendar.JULY, 1);
TimeZoneTransition tzt1 = otz.getNextTransition(base, true);
TimeZoneTransition tzt2 = vtz.getNextTransition(base, true);
if (tzt1.equals(tzt2)) {
errln("FAIL: getNextTransition returned different results in VTimeZone and OlsonTimeZone");
}
tzt1 = otz.getPreviousTransition(base, false);
tzt2 = vtz.getPreviousTransition(base, false);
if (tzt1.equals(tzt2)) {
errln("FAIL: getPreviousTransition returned different results in VTimeZone and OlsonTimeZone");
}
// hasEquivalentTransitions
long time1 = getUTCMillis(1950, Calendar.JANUARY, 1);
long time2 = getUTCMillis(2020, Calendar.JANUARY, 1);
if (!vtz.hasEquivalentTransitions(otz, time1, time2)) {
errln("FAIL: hasEquivalentTransitons returned false for the same time zone");
}
// getTimeZoneRules
TimeZoneRule[] rulesetAll = vtz.getTimeZoneRules();
TimeZoneRule[] ruleset1 = vtz.getTimeZoneRules(time1);
TimeZoneRule[] ruleset2 = vtz.getTimeZoneRules(time2);
if (rulesetAll.length < ruleset1.length || ruleset1.length < ruleset2.length) {
errln("FAIL: Number of rules returned by getRules is invalid");
}
int[] offsets_vtzc = new int[2];
VTimeZone vtzc = VTimeZone.create("PST");
vtzc.getOffsetFromLocal(Calendar.getInstance(vtzc).getTimeInMillis(), VTimeZone.LOCAL_STD, VTimeZone.LOCAL_STD, offsets_vtzc);
if (offsets_vtzc[0] > offsets_vtzc[1]) {
errln("Error getOffsetFromLocal()");
}
}
use of android.icu.util.BasicTimeZone in project j2objc by google.
the class TimeZoneRuleTest method TestBasicTimeZoneCoverage.
@Test
public void TestBasicTimeZoneCoverage() {
TimeZone tz = TimeZone.getTimeZone("PST");
if (tz instanceof BasicTimeZone) {
BasicTimeZone btz = (BasicTimeZone) tz;
int[] offsets = new int[2];
btz.getOffsetFromLocal(Calendar.getInstance().getTimeInMillis(), BasicTimeZone.LOCAL_STD, BasicTimeZone.LOCAL_STD, offsets);
if (offsets[0] > offsets[1]) {
errln("Error calling getOffsetFromLocal().");
}
} else {
logln("Skipping TestBasicTimeZoneCoverage: ICU4J is configured to use JDK TimeZone");
}
}
Aggregations