Java Code Examples for java.util.TimeZone#getTimeZone()

The following examples show how to use java.util.TimeZone#getTimeZone() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecondTest.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Some checks for the getLastMillisecond(TimeZone) method.
 */
@Test
public void testGetLastMillisecondWithTimeZone() {
    Second s = new Second(55, 1, 2, 7, 7, 1950);
    TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles");
    assertEquals(-614962684001L, s.getLastMillisecond(zone));

    // try null calendar
    boolean pass = false;
    try {
        s.getLastMillisecond((TimeZone) null);
    }
    catch (NullPointerException e) {
        pass = true;
    }
    assertTrue(pass);
}
 
Example 2
Source File: DateUtilsTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testIsSameLocalTime_Cal() {
    final GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
    final GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1"));
    cal1.set(2004, 6, 9, 13, 45, 0);
    cal1.set(Calendar.MILLISECOND, 0);
    cal2.set(2004, 6, 9, 13, 45, 0);
    cal2.set(Calendar.MILLISECOND, 0);
    assertTrue(DateUtils.isSameLocalTime(cal1, cal2));

    final Calendar cal3 = Calendar.getInstance();
    final Calendar cal4 = Calendar.getInstance();
    cal3.set(2004, 6, 9, 4,  0, 0);
    cal4.set(2004, 6, 9, 16, 0, 0);
    cal3.set(Calendar.MILLISECOND, 0);
    cal4.set(Calendar.MILLISECOND, 0);
    assertFalse("LANG-677", DateUtils.isSameLocalTime(cal3, cal4));
    
    cal2.set(2004, 6, 9, 11, 45, 0);
    assertFalse(DateUtils.isSameLocalTime(cal1, cal2));
    try {
        DateUtils.isSameLocalTime((Calendar) null, (Calendar) null);
        fail();
    } catch (final IllegalArgumentException ex) {}
}
 
Example 3
Source File: TimeZoneConstructor.java    From big-c with Apache License 2.0 6 votes vote down vote up
private Object createInfoFromDateutilTzfile(Object[] args) {
	if (args.length != 1)
		throw new PickleException("invalid pickle data for dateutil tzfile timezone; expected 1 args, got " + args.length);

	// In the case of the dateutil.tz.tzfile constructor, which is a python subclass of the datetime.tzinfo class, we're passed a
	// fully qualified path to a zoneinfo file. Extract the actual identifier as the part after the "zoneinfo" folder in the
	// absolute path.
	String identifier = (String) args[0];
	int index = identifier.indexOf("zoneinfo");
	if (index != -1) {
		identifier = identifier.substring(index + 8 + 1);
	} else {
		throw new PickleException("couldn't parse timezone identifier from zoneinfo path" + identifier);
	}
	return new Tzinfo(TimeZone.getTimeZone(identifier));
}
 
Example 4
Source File: MillisecondTest.java    From SIMVA-SoS with Apache License 2.0 6 votes vote down vote up
/**
 * Some checks for the getFirstMillisecond(TimeZone) method.
 */
@Test
public void testGetFirstMillisecondWithTimeZone() {
    Millisecond m = new Millisecond(500, 50, 59, 15, 1, 4, 1950);
    TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles");
    assertEquals(-623289609500L, m.getFirstMillisecond(zone));

    // try null calendar
    boolean pass = false;
    try {
        m.getFirstMillisecond((TimeZone) null);
    }
    catch (NullPointerException e) {
        pass = true;
    }
    assertTrue(pass);
}
 
Example 5
Source File: QuarterTests.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Some checks for the getLastMillisecond(TimeZone) method.
 */
public void testGetLastMillisecondWithTimeZone() {
    Quarter q = new Quarter(2, 1950);
    TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles");
    Calendar c = new GregorianCalendar(zone);
    assertEquals(-615488400001L, q.getLastMillisecond(c));

    // try null calendar
    boolean pass = false;
    try {
        q.getLastMillisecond((Calendar) null);
    }
    catch (NullPointerException e) {
        pass = true;
    }
    assertTrue(pass);
}
 
Example 6
Source File: UserPrefsTool.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * @param selectedTimeZone
 *        The selectedTimeZone to set.
 */
public void setSelectedTimeZone(String selectedTimeZone)
{
	if (selectedTimeZone != null)
		m_timeZone = TimeZone.getTimeZone(selectedTimeZone);
	else
		log.warn(this + "setSelctedTimeZone() has null TimeZone");
}
 
Example 7
Source File: JsonLineDeserializer.java    From tajo with Apache License 2.0 5 votes vote down vote up
public JsonLineDeserializer(Schema schema, TableMeta meta, Column [] projected) {
  super(schema, meta);

  projectedPaths = SchemaUtil.convertColumnsToPaths(Lists.newArrayList(projected), true);
  types = SchemaUtil.buildTypeMap(schema.getAllColumns(), projectedPaths);

  timezone = TimeZone.getTimeZone(meta.getProperty(StorageConstants.TIMEZONE,
      StorageUtil.TAJO_CONF.getSystemTimezone().getID()));
}
 
Example 8
Source File: GregorianCalendarTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.util.GregorianCalendar#GregorianCalendar(java.util.TimeZone)
 */
public void test_ConstructorLjava_util_TimeZone() {
    // Test for method java.util.GregorianCalendar(java.util.TimeZone)
    Date date = new Date(2008, 1, 1);
    TimeZone.getDefault();
    GregorianCalendar gc1 = new GregorianCalendar(AMERICA_NEW_YORK);
    gc1.setTime(date);
    GregorianCalendar gc2 = new GregorianCalendar(AMERICA_CHICAGO);
    gc2.setTime(date);
    // Chicago is 1 hour before New York, add 1 to the Chicago time and convert to 0-12 value
    assertEquals("Incorrect calendar returned",
            gc1.get(Calendar.HOUR), ((gc2.get(Calendar.HOUR) + 1) % 12));

    // Regression test for HARMONY-2961
    SimpleTimeZone timezone = new SimpleTimeZone(-3600 * 24 * 1000 * 2,
            "GMT");
    GregorianCalendar gc = new GregorianCalendar(timezone);

    // Regression test for HARMONY-5195
    Calendar c1 = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    c1.set(Calendar.YEAR, 1999);
    c1.set(Calendar.MONTH, Calendar.JUNE);
    c1.set(Calendar.DAY_OF_MONTH, 2);
    c1.set(Calendar.HOUR, 15);
    c1.set(Calendar.MINUTE, 34);
    c1.set(Calendar.SECOND, 16);
    assertEquals(34, c1.get(Calendar.MINUTE));
    c1.setTimeZone(new SimpleTimeZone(60000, "ONE MINUTE"));
    assertEquals(35, c1.get(Calendar.MINUTE));
}
 
Example 9
Source File: Data.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public TimeZone getTimeZone (String timezone) {
	if (timezone == null) {
		timezone = company.info ("locale-timezone", mailing.id ());
	}
	if (timezone == null) {
		return null;
	}
	return TimeZone.getTimeZone (timezone);
}
 
Example 10
Source File: ReportJsonService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@GET(path = "/backend/report/transaction-types-and-gauges", permission = "")
String getAllGauges(@BindRequest TransactionTypesAndGaugesRequest request,
        @BindAuthentication Authentication authentication) throws Exception {
    checkPermissions(request.agentRollupIds(), "agent:transaction:overview", authentication);
    checkPermissions(request.agentRollupIds(), "agent:jvm:gauges", authentication);

    TimeZone timeZone = TimeZone.getTimeZone(request.timeZoneId());
    FromToPair fromToPair = parseDates(request.fromDate(), request.toDate(), timeZone);
    Date from = fromToPair.from();
    Date to = fromToPair.to();

    Set<String> transactionTypes = Sets.newTreeSet();
    Set<Gauge> gauges = Sets.newHashSet();
    for (String agentRollupId : request.agentRollupIds()) {
        transactionTypes.addAll(transactionTypeRepository.read(agentRollupId));
        transactionTypes.addAll(liveAggregateRepository.getTransactionTypes(agentRollupId));
        try {
            transactionTypes.add(configRepository.getUiDefaultsConfig(agentRollupId)
                    .getDefaultTransactionType());
        } catch (AgentConfigNotFoundException e) {
            logger.debug(e.getMessage(), e);
        }
        gauges.addAll(
                gaugeValueRepository.getGauges(agentRollupId, from.getTime(), to.getTime()));
    }
    return mapper.writeValueAsString(ImmutableTransactionTypesAndGaugesReponse.builder()
            .addAllTransactionTypes(transactionTypes)
            .addAllGauges(new GaugeOrdering().sortedCopy(gauges))
            .build());
}
 
Example 11
Source File: TimestampTest.java    From ion-java with Apache License 2.0 5 votes vote down vote up
@Ignore // TODO ion-java#165
@Test
public void testCustomCalendarLeapYearAfterWithLocalOffset() {
    // Create a purely Julian calendar, where leap years were every four years.
    GregorianCalendar julianCalendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    julianCalendar.setGregorianChange(new Date(Long.MAX_VALUE));
    julianCalendar.clear();
    // 1800 is not a leap year under the Gregorian calendar, but it is under the Julian calendar.
    julianCalendar.set(1800, Calendar.FEBRUARY, 28, 23, 59, 59);
    Timestamp timestamp1 = Timestamp.forCalendar(julianCalendar);
    Timestamp timestamp2 = timestamp1.withLocalOffset(0).addSecond(1);
    assertEquals("1800-02-29T00:00:00Z", timestamp2.toString());
}
 
Example 12
Source File: SimpleDateFormat.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * find time zone 'text' matched zoneStrings and set to internal
 * calendar.
 */
private int subParseZoneString(String text, int start, CalendarBuilder calb) {
    boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
    TimeZone currentTimeZone = getTimeZone();

    // At this point, check for named time zones by looking through
    // the locale data from the TimeZoneNames strings.
    // Want to be able to parse both short and long forms.
    int zoneIndex = formatData.getZoneIndex(currentTimeZone.getID());
    TimeZone tz = null;
    String[][] zoneStrings = formatData.getZoneStringsWrapper();
    String[] zoneNames = null;
    int nameIndex = 0;
    if (zoneIndex != -1) {
        zoneNames = zoneStrings[zoneIndex];
        if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
            if (nameIndex <= 2) {
                // Check if the standard name (abbr) and the daylight name are the same.
                useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
            }
            tz = TimeZone.getTimeZone(zoneNames[0]);
        }
    }
    if (tz == null) {
        zoneIndex = formatData.getZoneIndex(TimeZone.getDefault().getID());
        if (zoneIndex != -1) {
            zoneNames = zoneStrings[zoneIndex];
            if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
                if (nameIndex <= 2) {
                    useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
                }
                tz = TimeZone.getTimeZone(zoneNames[0]);
            }
        }
    }

    if (tz == null) {
        int len = zoneStrings.length;
        for (int i = 0; i < len; i++) {
            zoneNames = zoneStrings[i];
            if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
                if (nameIndex <= 2) {
                    useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
                }
                tz = TimeZone.getTimeZone(zoneNames[0]);
                break;
            }
        }
    }
    if (tz != null) { // Matched any ?
        if (!tz.equals(currentTimeZone)) {
            setTimeZone(tz);
        }
        // If the time zone matched uses the same name
        // (abbreviation) for both standard and daylight time,
        // let the time zone in the Calendar decide which one.
        //
        // Also if tz.getDSTSaving() returns 0 for DST, use tz to
        // determine the local time. (6645292)
        int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
        if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
            calb.clear(Calendar.ZONE_OFFSET).set(Calendar.DST_OFFSET, dstAmount);
        }
        return (start + zoneNames[nameIndex].length());
    }
    return -start;
}
 
Example 13
Source File: NotesTimeDate.java    From domino-jna with Apache License 2.0 4 votes vote down vote up
public TimeZone getTimeZone() {
	if (m_guessedTimezone==null) {
		if (m_innards[1] == NotesConstants.ANYDAY) {
			return null;
		}

		long innard1Long = m_innards[1];

		int tzSign;
		if (((innard1Long >> 30) & 1 ) == 0) {
			tzSign = -1;
		}
		else {
			tzSign = 1;
		}

		//The high-order bit, bit 31 (0x80000000), is set if Daylight Savings Time is observed
		boolean useDST;
		if (((innard1Long >> 31) & 1 ) == 0) {
			useDST = false;
		}
		else {
			useDST = true;
		}

		int tzOffsetHours = (int) (innard1Long >> 24) & 0xF;
		int tzOffsetFraction15MinuteIntervalls = (int) (innard1Long >> 28) & 0x3;

		long rawOffsetMillis = tzSign * 1000 * (tzOffsetHours * 60 * 60 + 15*60*tzOffsetFraction15MinuteIntervalls);

		if (rawOffsetMillis==0) {
			m_guessedTimezone = TimeZone.getTimeZone("GMT");
		}
		else {
			//not great, go through the JDK locales to find a matching one by comparing the 
			//raw offset; grep its short id and try to load a TimeZone for it
			//the purpose is to return short ids like "CET" instead of "Africa/Ceuta"
			String[] timezonesWithOffset = TimeZone.getAvailableIDs((int) rawOffsetMillis);
			for (String currTZID : timezonesWithOffset) {
				TimeZone currTZ = TimeZone.getTimeZone(currTZID);
				if (useDST==currTZ.useDaylightTime()) {
					String tzShortId = currTZ.getDisplayName(false, TimeZone.SHORT, Locale.ENGLISH);
					m_guessedTimezone = TimeZone.getTimeZone(tzShortId);
					if ("GMT".equals(m_guessedTimezone.getID())) {
						//parse failed
						m_guessedTimezone = currTZ;
					}
					break;
				}
			}

			if (m_guessedTimezone==null) {
				String tzString = "GMT" + (tzSign < 0 ? "-" : "+") +
						StringUtil.pad(Integer.toString(tzOffsetHours + (useDST ? 1 : 0)), 2, '0', false) + ":" +
						StringUtil.pad(Integer.toString(15 * tzOffsetFraction15MinuteIntervalls), 2, '0', false);

				m_guessedTimezone = TimeZone.getTimeZone(tzString);
			}
		}
	}
	return m_guessedTimezone;
}
 
Example 14
Source File: Bug4858517.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {

        Locale tzLocale;

        for (int i = 0; i < locales2Test.length; i++){

            tzLocale = locales2Test[i];
            TimeZone Rothera = TimeZone.getTimeZone("Antarctica/Rothera");

            if (!Rothera.getDisplayName(false, TimeZone.SHORT, tzLocale).equals ("ROTT"))
                throw new RuntimeException("\n" + tzLocale + ": short name, non-daylight time for Rothera should be \"ROTT\"");

            if (!Rothera.getDisplayName(true, TimeZone.SHORT, tzLocale).equals ("ROTST"))
                throw new RuntimeException("\n" + tzLocale + ": short name, daylight time for Rothera should be \"ROTST\"");

            TimeZone IRT = TimeZone.getTimeZone("Iran");

            if (!IRT.getDisplayName(false, TimeZone.SHORT, tzLocale).equals ("IRST"))
                throw new RuntimeException("\n" + tzLocale + ": short name, non-daylight time for IRT should be \"IRST\"");

            if (!IRT.getDisplayName(true, TimeZone.SHORT, tzLocale).equals ("IRDT"))
             throw new RuntimeException("\n" + tzLocale + ": short name, daylight time for IRT should be \"IRDT\"");
        }

   }
 
Example 15
Source File: SimCalendar.java    From jaamsim with Apache License 2.0 4 votes vote down vote up
public SimCalendar() {
	super(TimeZone.getTimeZone( "GMT" ));
}
 
Example 16
Source File: PatternLayout.java    From gflogger with Apache License 2.0 4 votes vote down vote up
public PatternLayout(final String pattern, final String timeZoneId) {
	this(pattern, timeZoneId != null ? TimeZone.getTimeZone(timeZoneId) : null, null);
}
 
Example 17
Source File: DateUtilsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
protected void setUp() throws Exception {
    super.setUp();

    dateParser = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH);
    dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH);

    dateAmPm1 = dateTimeParser.parse("February 3, 2002 01:10:00.000");
    dateAmPm2 = dateTimeParser.parse("February 3, 2002 11:10:00.000");
    dateAmPm3 = dateTimeParser.parse("February 3, 2002 13:10:00.000");
    dateAmPm4 = dateTimeParser.parse("February 3, 2002 19:10:00.000");
    date0 = dateTimeParser.parse("February 3, 2002 12:34:56.789");
    date1 = dateTimeParser.parse("February 12, 2002 12:34:56.789");
    date2 = dateTimeParser.parse("November 18, 2001 1:23:11.321");
    defaultZone = TimeZone.getDefault();
    zone = TimeZone.getTimeZone("MET");
    TimeZone.setDefault(zone);
    dateTimeParser.setTimeZone(zone);
    date3 = dateTimeParser.parse("March 30, 2003 05:30:45.000");
    date4 = dateTimeParser.parse("March 30, 2003 01:10:00.000");
    date5 = dateTimeParser.parse("March 30, 2003 01:40:00.000");
    date6 = dateTimeParser.parse("March 30, 2003 02:10:00.000");
    date7 = dateTimeParser.parse("March 30, 2003 02:40:00.000");
    date8 = dateTimeParser.parse("October 26, 2003 05:30:45.000");
    dateTimeParser.setTimeZone(defaultZone);
    TimeZone.setDefault(defaultZone);
    calAmPm1 = Calendar.getInstance();
    calAmPm1.setTime(dateAmPm1);
    calAmPm2 = Calendar.getInstance();
    calAmPm2.setTime(dateAmPm2);
    calAmPm3 = Calendar.getInstance();
    calAmPm3.setTime(dateAmPm3);
    calAmPm4 = Calendar.getInstance();
    calAmPm4.setTime(dateAmPm4);
    cal1 = Calendar.getInstance();
    cal1.setTime(date1);
    cal2 = Calendar.getInstance();
    cal2.setTime(date2);
    TimeZone.setDefault(zone);
    cal3 = Calendar.getInstance();
    cal3.setTime(date3);
    cal4 = Calendar.getInstance();
    cal4.setTime(date4);
    cal5 = Calendar.getInstance();
    cal5.setTime(date5);
    cal6 = Calendar.getInstance();
    cal6.setTime(date6);
    cal7 = Calendar.getInstance();
    cal7.setTime(date7);
    cal8 = Calendar.getInstance();
    cal8.setTime(date8);
    TimeZone.setDefault(defaultZone);
}
 
Example 18
Source File: ConnectionTest.java    From Komondor with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Test connection property cacheDefaultTimezone.
 * 
 * @throws SQLException
 */
public void testCacheDefaultTimezone() throws Exception {
    final TimeZone defaultTZ = TimeZone.getDefault();
    final TimeZone testTZ1 = TimeZone.getTimeZone("GMT-2");
    final TimeZone testTZ2 = TimeZone.getTimeZone("GMT+2");

    createTable("testCacheDefTZ", "(test TINYINT, dt DATETIME)");

    Properties connProps = new Properties();
    connProps.setProperty("useTimezone", "true");

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    for (boolean cacheDefTZ : new boolean[] { true, false }) {
        try {
            String testMsg = "Test case [cacheDefaultTimezone=" + cacheDefTZ + "],";
            connProps.setProperty("cacheDefaultTimezone", Boolean.toString(cacheDefTZ));

            Connection testConn = getConnectionWithProps(connProps);
            PreparedStatement testPstmt = testConn.prepareStatement("INSERT INTO testCacheDefTZ VALUES (?, ?)");

            sdf.setTimeZone(testTZ1);
            java.sql.Timestamp tsIn = new java.sql.Timestamp(sdf.parse("1998-05-21 12:00:00").getTime());

            /*
             * Insert same date/time instant twice using different default time zones.
             * Same values must be stored when default time zone is cached. Different values otherwise.
             */
            TimeZone.setDefault(testTZ1);
            testPstmt.setBoolean(1, cacheDefTZ);
            testPstmt.setTimestamp(2, tsIn);
            assertEquals(testMsg, 1, testPstmt.executeUpdate());

            TimeZone.setDefault(testTZ2);
            testPstmt.setBoolean(1, cacheDefTZ);
            testPstmt.setTimestamp(2, tsIn);
            assertEquals(testMsg, 1, testPstmt.executeUpdate());

            testPstmt.close();

            TimeZone.setDefault(defaultTZ);

            /*
             * Verify that equal values are retrieved when default time zone is cached and different values otherwise, when default time zone doesn't
             * change while reading data.
             */
            Statement testStmt = testConn.createStatement();
            ResultSet testRs = testStmt.executeQuery("SELECT * FROM testCacheDefTZ WHERE test = " + cacheDefTZ);

            assertTrue(testMsg, testRs.next());
            java.sql.Timestamp timestampOut = testRs.getTimestamp(2);

            assertTrue(testMsg, testRs.next());
            assertEquals(testMsg, cacheDefTZ, timestampOut.equals(testRs.getTimestamp(2)));

            assertFalse(testMsg, testRs.next());

            /*
             * Verify that retrieving values from the ResultSet is also affected by default time zone caching setting, allowing to "convert" them to the
             * original date value when time zone caching is disabled.
             * When time zone caching is enabled then the values stored in the database were the same and changing the default time zone while retrieving
             * them doesn't affect the result.
             */
            testRs = testStmt.executeQuery("SELECT * FROM testCacheDefTZ WHERE test = " + cacheDefTZ);

            TimeZone.setDefault(testTZ1);
            assertTrue(testMsg, testRs.next());
            timestampOut = testRs.getTimestamp(2);

            TimeZone.setDefault(testTZ2);
            assertTrue(testMsg, testRs.next());
            assertEquals(testMsg, timestampOut, testRs.getTimestamp(2));

            assertFalse(testMsg, testRs.next());

            testRs.close();
            testStmt.close();

            testConn.close();
        } finally {
            TimeZone.setDefault(defaultTZ);
        }
    }
}
 
Example 19
Source File: SimpleDateFormat.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * find time zone 'text' matched zoneStrings and set to internal
 * calendar.
 */
private int subParseZoneString(String text, int start, CalendarBuilder calb) {
    boolean useSameName = false; // true if standard and daylight time use the same abbreviation.
    TimeZone currentTimeZone = getTimeZone();

    // At this point, check for named time zones by looking through
    // the locale data from the TimeZoneNames strings.
    // Want to be able to parse both short and long forms.
    int zoneIndex = formatData.getZoneIndex(currentTimeZone.getID());
    TimeZone tz = null;
    String[][] zoneStrings = formatData.getZoneStringsWrapper();
    String[] zoneNames = null;
    int nameIndex = 0;
    if (zoneIndex != -1) {
        zoneNames = zoneStrings[zoneIndex];
        if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
            if (nameIndex <= 2) {
                // Check if the standard name (abbr) and the daylight name are the same.
                useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
            }
            tz = TimeZone.getTimeZone(zoneNames[0]);
        }
    }
    if (tz == null) {
        zoneIndex = formatData.getZoneIndex(TimeZone.getDefault().getID());
        if (zoneIndex != -1) {
            zoneNames = zoneStrings[zoneIndex];
            if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
                if (nameIndex <= 2) {
                    useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
                }
                tz = TimeZone.getTimeZone(zoneNames[0]);
            }
        }
    }

    if (tz == null) {
        int len = zoneStrings.length;
        for (int i = 0; i < len; i++) {
            zoneNames = zoneStrings[i];
            if ((nameIndex = matchZoneString(text, start, zoneNames)) > 0) {
                if (nameIndex <= 2) {
                    useSameName = zoneNames[nameIndex].equalsIgnoreCase(zoneNames[nameIndex + 2]);
                }
                tz = TimeZone.getTimeZone(zoneNames[0]);
                break;
            }
        }
    }
    if (tz != null) { // Matched any ?
        if (!tz.equals(currentTimeZone)) {
            setTimeZone(tz);
        }
        // If the time zone matched uses the same name
        // (abbreviation) for both standard and daylight time,
        // let the time zone in the Calendar decide which one.
        //
        // Also if tz.getDSTSaving() returns 0 for DST, use tz to
        // determine the local time. (6645292)
        int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0;
        if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) {
            calb.clear(Calendar.ZONE_OFFSET).set(Calendar.DST_OFFSET, dstAmount);
        }
        return (start + zoneNames[nameIndex].length());
    }
    return -start;
}
 
Example 20
Source File: TimezoneUtil.java    From openmeetings with Apache License 2.0 2 votes vote down vote up
/**
 *
 * @param timeZoneId
 *            the ID for a TimeZone, either an abbreviation such as "PST", a
 *            full name such as "America/Los_Angeles", or a custom ID such as
 *            "GMT-8:00". Note that the support of abbreviations is for JDK
 *            1.1.x compatibility only and full names should be used.
 * @return the specified TimeZone, or the GMT zone if the given ID cannot be
 *         understood.
 */
public static TimeZone getTimeZone(String timeZoneId) {
	return TimeZone.getTimeZone(Strings.isEmpty(timeZoneId) ? getDefaultTimezone() : timeZoneId);
}