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

The following examples show how to use java.util.TimeZone#setDefault() . These examples are extracted from open source projects. 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
@Test
public void testTimeStampUtc() throws SQLException {

  TimeZone.setDefault(parisTimeZone);
  try (Connection connection = setConnection("&serverTimezone=UTC&useServerPrepStmts=true")) {
    setSessionTimeZone(connection, "+00:00");
    // timestamp timezone to parisTimeZone like server
    Timestamp currentTimeParis = new Timestamp(System.currentTimeMillis());
    PreparedStatement st = connection.prepareStatement("SELECT ?");
    st.setTimestamp(1, currentTimeParis);
    ResultSet rs = st.executeQuery();
    assertTrue(rs.next());
    Timestamp t1 = rs.getTimestamp(1);
    assertEquals(t1, currentTimeParis);
  }
}
 
Example 2
Source Project: FlowGeek   File: Utilities.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static String dateFormat(String strdate) throws ParseException {
    if (isEmpty(strdate))return null;

    TimeZone tz =TimeZone.getTimeZone("Asia/Shanghai");
    TimeZone.setDefault(tz);
    long timestamp = System.currentTimeMillis() - new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).parse(strdate).getTime();
    if (0 <= timestamp && timestamp < 60 * 60 * 1000) {
        // 几分钟之前
        return timestamp / (60 * 1000) + "分钟之前";
    }else if (60 * 60 * 1000 <= timestamp && timestamp < 24 * 60 * 60 * 1000) {
        // 几小时之前
        return timestamp / (60 * 60 * 1000) + "小时之前";
    }else if (24 * 60 * 60 * 1000 <= timestamp && timestamp < (long)30 * 24 * 60 * 60 * 1000) {
        // 几天前
        return timestamp / (24 * 60 * 60 * 1000) + "天之前";
    }else if ((long)31 * 24 * 60 * 60 * 1000 < timestamp && timestamp < (long)12 * 30 * 24 * 60 * 60 * 1000) {
        // 几个月之前
        return timestamp / (long)30 * 24 * 60 * 60 * 1000 + "月之前";
    }else{
        return strdate;
    }
}
 
Example 3
/**
 * Takes a JarInputStream and converts into a pack-stream.
 * <p>
 * Closes its input but not its output.  (Pack200 archives are appendable.)
 * <p>
 * The modification time and deflation hint attributes are not available,
 * for the jar-manifest file and the directory containing the file.
 *
 * @see #MODIFICATION_TIME
 * @see #DEFLATION_HINT
 * @param in a JarInputStream
 * @param out an OutputStream
 * @exception IOException if an error is encountered.
 */
public synchronized void pack(JarInputStream in, OutputStream out) throws IOException {
    assert(Utils.currentInstance.get() == null);
    TimeZone tz = (props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE)) ? null :
        TimeZone.getDefault();
    try {
        Utils.currentInstance.set(this);
        if (tz != null) TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        if ("0".equals(props.getProperty(Pack200.Packer.EFFORT))) {
            Utils.copyJarFile(in, out);
        } else {
            (new DoPack()).run(in, out);
        }
    } finally {
        Utils.currentInstance.set(null);
        if (tz != null) TimeZone.setDefault(tz);
        in.close();
    }
}
 
Example 4
public static void main(String[] args)   {
    TimeZone defaultZone = TimeZone.getDefault();

    // Make sure that TimeZone.setDefault works for trusted code
    TimeZone.setDefault(NOWHERE);
    if (!NOWHERE.equals(TimeZone.getDefault())) {
        new RuntimeException("TimeZone.setDefault doesn't work for trusted code.");
    }
    // Restore defaultZone
    TimeZone.setDefault(defaultZone);
    if (!defaultZone.equals(TimeZone.getDefault())) {
        new RuntimeException("TimeZone.setDefault doesn't restore defaultZone.");
    }

    // Install a SecurityManager.
    System.setSecurityManager(new SecurityManager());
    try {
        TimeZone.setDefault(NOWHERE);
        throw new RuntimeException("TimeZone.setDefault doesn't throw a SecurityException.");
    } catch (SecurityException se) {
        // OK
    }
    TimeZone tz = TimeZone.getDefault();
    if (!defaultZone.equals(tz)) {
        throw new RuntimeException("Default TimeZone changed: " + tz);
    }
}
 
Example 5
@Test
public void parseDate() {
  // Date assertions don't assume UTC
  TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

  long date = ZipkinDependenciesJob.parseDay("2013-05-15");
  assertThat(new Date(date))
      .hasYear(2013)
      .hasMonth(5)
      .hasDayOfMonth(15)
      .hasHourOfDay(0)
      .hasMinute(0)
      .hasSecond(0)
      .hasMillisecond(0);
}
 
Example 6
protected void setUp() throws Exception {
    DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
    originalDateTimeZone = DateTimeZone.getDefault();
    originalTimeZone = TimeZone.getDefault();
    originalLocale = Locale.getDefault();
    DateTimeZone.setDefault(PARIS);
    TimeZone.setDefault(PARIS.toTimeZone());
    Locale.setDefault(Locale.FRANCE);
}
 
Example 7
Source Project: rya   File: RyaDetailsFormatterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void format_mongo() {
    // This test failed if the default timezone was not EST, so now it's fixed at EST.
    TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
    // Create the object that will be formatted.
    final RyaDetails details = RyaDetails.builder().setRyaInstanceName("test_instance")
        .setRyaVersion("1.2.3.4")
        .setEntityCentricIndexDetails(new EntityCentricIndexDetails(false))
      //RYA-215            .setGeoIndexDetails( new GeoIndexDetails(true) )
        .setTemporalIndexDetails( new TemporalIndexDetails(true) )
        .setFreeTextDetails( new FreeTextIndexDetails(true) )
        .setPCJIndexDetails(PCJIndexDetails.builder().setEnabled(true))
        .setProspectorDetails( new ProspectorDetails(Optional.absent()) )
        .setJoinSelectivityDetails( new JoinSelectivityDetails(Optional.absent()) )
        .build();

    final String formatted = new RyaDetailsFormatter().format(StorageType.MONGO, details);

    // Verify the created object matches the expected result.
    final String expected =
            "General Metadata:\n" +
            "  Instance Name: test_instance\n" +
            "  RYA Version: 1.2.3.4\n" +
            "Secondary Indicies:\n" +
        //RYA-215                "  Geospatial Index:\n" +
        //RYA-215                "    Enabled: true\n" +
            "  Free Text Index:\n" +
            "    Enabled: true\n" +
            "  Temporal Index:\n" +
            "    Enabled: true\n" +
            "  PCJ Index:\n" +
            "    Enabled: true\n" +
            "    PCJs:\n" +
            "      No PCJs have been added yet.\n";

    assertEquals(expected, formatted);
}
 
Example 8
@AfterAll
public static void reset() {
    TimeZone.setDefault(defaultTZ);

    try {
        Misc.deleteDirectorySimple(cloneDir);
    } catch (Exception ignore) {
        System.err.println("cannot remove " + cloneDir);
    }
}
 
Example 9
/**
 * Some checks for the getFirstMillisecond() method.
 */
@Test
public void testGetFirstMillisecond() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.UK);
    TimeZone savedZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Second s = new Second(15, 43, 15, 1, 4, 2006);
    assertEquals(1143902595000L, s.getFirstMillisecond());
    Locale.setDefault(saved);
    TimeZone.setDefault(savedZone);
}
 
Example 10
@Test
public void charge_creditCardSpecialCharacter() throws Exception {
    // setup
    TimeZone.setDefault(TimeZone.getTimeZone("GMT+1"));

    ChargingData chargingData = createChargingData();
    RequestData requestData = createRequestData(CREDIT_CARD);
    requestData
            .setOrganizationName("富士通 エ�ブリング ソフトウェア テクノロジー");
    PostMethodStub.setStubReturnValue(sampleResponse);

    // execute
    ChargingResult chargingResult = psp.charge(requestData, chargingData);

    // assert request xml
    NameValuePair[] requestBodyDetails = PostMethodStub
            .getRequestBodyDetails();
    validateRequestDetails(
            requestBodyDetails,
            "CC",
            "富士通 エ�ブリング ソフトウェア テクノロジー",
            "EUR", "1226.00");
    validateRequestAnalysisData(requestBodyDetails, "", chargingData);

    // assert xml response
    assertNotNull(
            "Operation passed, so the processing details must be contained in the billing result!",
            chargingResult.getProcessingResult());
    Document processingResult = XMLConverter.convertToDocument(
            chargingResult.getProcessingResult(), true);
    assertEquals(
            "Wrong result in processing result document",
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response version=\"1.0\"><Transaction mode=\"LIVE\" response=\"SYNC\" channel=\"678a456b789c123d456e789f012g432\"><Identification><TransactionID>MerchantAssignedID</TransactionID><UniqueID>h987i654j321k098l765m432n210o987</UniqueID><ShortID>1234.5678.9876</ShortID></Identification><Processing code=\"DD.DB.90.00\"><Timestamp>2003-02-12 14:58:07</Timestamp><Result>ACK</Result><Status code=\"90\">NEW</Status><Reason code=\"00\">Successful Processing</Reason><Return code=\"000.000.000\">Transaction succeeded</Return></Processing><Payment code=\"DD.DB\"><Clearing><Amount>1.00</Amount><Currency>EUR</Currency><Descriptor>shop.de 1234.1234.1234 +49 (89) 12345 678 Order Number 1234</Descriptor><Date>2003-02-13</Date><Support>+49 (89) 1234 567</Support></Clearing></Payment></Transaction></Response>",
            chargingResult.getProcessingResult());
    assertEquals("Wrong result in processing result document", "ACK",
            XMLConverter.getNodeTextContentByXPath(processingResult,
                    "/Response/Transaction/Processing/Result"));
}
 
Example 11
protected void tearDown() throws Exception {
    DateTimeUtils.setCurrentMillisSystem();
    DateTimeZone.setDefault(originalDateTimeZone);
    TimeZone.setDefault(originalTimeZone);
    Locale.setDefault(originalLocale);
    originalDateTimeZone = null;
    originalTimeZone = null;
    originalLocale = null;
}
 
Example 12
@Test(expectedExceptions = ZoneRulesException.class)
public void test_systemDefault_unableToConvert_unknownId() {
    TimeZone current = TimeZone.getDefault();
    try {
        TimeZone.setDefault(new SimpleTimeZone(127, "SomethingWeird"));
        ZoneId.systemDefault();
    } finally {
        TimeZone.setDefault(current);
    }
}
 
Example 13
@BeforeClass
public static void setUpClass() throws Exception {
    defaultTimeZone = TimeZone.getDefault();
    TimeZone tzone = TimeZone.getTimeZone("GMT+01");
    assertFalse(tzone.observesDaylightTime());
    TimeZone.setDefault(tzone);
}
 
Example 14
/**
 * Some checks for the getLastMillisecond() method.
 */
@Test
public void testGetLastMillisecond() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.UK);
    TimeZone savedZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Millisecond m = new Millisecond(750, 1, 1, 1, 1, 1, 1970);
    assertEquals(61750L, m.getLastMillisecond());
    Locale.setDefault(saved);
    TimeZone.setDefault(savedZone);
}
 
Example 15
Source Project: SIMVA-SoS   File: YearTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Some checks for the getLastMillisecond() method.
 */
@Test
public void testGetLastMillisecond() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.UK);
    TimeZone savedZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Year y = new Year(1970);
    // TODO: Check this result...
    assertEquals(31532399999L, y.getLastMillisecond());
    Locale.setDefault(saved);
    TimeZone.setDefault(savedZone);
}
 
Example 16
public static void main(String[] args) throws Exception {
    TimeZone tz = TimeZone.getDefault();
    Locale lc = Locale.getDefault();
    try {
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        Locale.setDefault(Locale.US);

        new GregorianCutoverTest().run(args);
    } finally {
        TimeZone.setDefault(tz);
        Locale.setDefault(lc);
    }
}
 
Example 17
@Test
public void testDateTimeConverter_configuredPatterns_dateOnly() throws IOException {
  when(mockIndexingService.getSchema()).thenReturn(new Schema());
  Properties config = new Properties();
  config.put(StructuredData.DATETIME_PATTERNS, "M/d/yy ;dd MMM uuuu");
  setupConfig.initConfig(config);
  StructuredData.initFromConfiguration(mockIndexingService);

  TimeZone original = TimeZone.getDefault();
  TimeZone.setDefault(TimeZone.getTimeZone("GMT-04:00"));
  try {
    String rfc3339String = "2018-08-08T00:00:00.000-04:00";
    DateTime expected = new DateTime(rfc3339String);
    // Baseline so we don't chase unexpected errors below.
    assertEquals("Baseline failure", rfc3339String, expected.toString());

    Converter<Object, DateTime> converter = StructuredData.DATETIME_CONVERTER;
    for (String dateString : new String[] {
          "2018-08-08-04:00",
          "Wed, 8 Aug 2018 00:00:00 -0400",
          "8/8/18",
          "08 aUg 2018",
        }) {
      try {
        collector.checkThat(dateString, converter.convert(dateString), equalTo(expected));
      } catch (NumberFormatException e) {
        collector.addError(e);
      }
    }
  } finally {
    TimeZone.setDefault(original);
  }
}
 
Example 18
@Test(expectedExceptions = DateTimeException.class)
public void test_systemDefault_unableToConvert_badFormat() {
    TimeZone current = TimeZone.getDefault();
    try {
        TimeZone.setDefault(new SimpleTimeZone(127, "Something Weird"));
        ZoneId.systemDefault();
    } finally {
        TimeZone.setDefault(current);
    }
}
 
Example 19
/**
 * Test 7 checks 9am Monday 29 March 2004 converts to a timeline value and
 * back again correctly.  This is during Daylight Saving.
 */
@Test
public void test7() {
    TimeZone savedZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Calendar cal = Calendar.getInstance(Locale.UK);
    cal.set(Calendar.YEAR, 2004);
    cal.set(Calendar.MONTH, Calendar.MARCH);
    cal.set(Calendar.DAY_OF_MONTH, 29);
    cal.set(Calendar.HOUR_OF_DAY, 9);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Date date = cal.getTime();

    SegmentedTimeline timeline = getTimeline();
    long value = timeline.toTimelineValue(date);
    long ms = timeline.toMillisecond(value);

    Calendar cal2 = Calendar.getInstance(Locale.UK);
    cal2.setTime(new Date(ms));
    Date reverted = cal2.getTime();

    Calendar expectedReverted = Calendar.getInstance();
    expectedReverted.set(Calendar.YEAR, 2004);
    expectedReverted.set(Calendar.MONTH, Calendar.MARCH);
    expectedReverted.set(Calendar.DAY_OF_MONTH, 29);
    expectedReverted.set(Calendar.HOUR_OF_DAY, 9);
    expectedReverted.set(Calendar.MINUTE, 0);
    expectedReverted.set(Calendar.SECOND, 0);
    expectedReverted.set(Calendar.MILLISECOND, 0);

    assertTrue("test7", value == (900000 * 34 * 2)
            && expectedReverted.getTime().getTime() == reverted.getTime());
    TimeZone.setDefault(savedZone);
}
 
Example 20
/**
 * short time zone like [CST, PST], may raise some problem (issue#13185).
 * TimeZone.ID & TimeZone.ZoneId.ID set same data, like [Asia/Shanghai, America/New_York].
 *
 * @param kylinConfig
 */
public static void setDefaultTimeZone(KylinConfig kylinConfig) {
    ZoneId zoneId = TimeZone.getTimeZone(kylinConfig.getTimeZone()).toZoneId();
    TimeZone.setDefault(TimeZone.getTimeZone(zoneId));
    log.info("System timezone set to {}, TimeZoneId: {}.", kylinConfig.getTimeZone(), TimeZone.getDefault().getID());
}