Exemple #1
1
  public static Calendar UTC2Calendar(String dateTime) throws UtilitiesException {
    Matcher m = UTC_PATTERNER.matcher(dateTime);
    if (m.matches() && m.groupCount() == 9) {
      int parts[] = new int[8];
      int i;
      for (i = 0; i < 6; i++) parts[i] = Integer.parseInt(m.group(i + 1));

      String ms = m.group(i + 1);
      if (ms == null) {
        parts[i++] = 0;
      } else {
        if (ms.length() > 3) ms = ms.substring(0, 3);
        parts[i++] = Integer.parseInt(ms);
      }
      String tzStr = m.group(i + 1);
      TimeZone tz = null;
      if (tzStr == null || tzStr.equals("Z")) tz = TimeZone.getTimeZone("UTC");
      else tz = TimeZone.getTimeZone("GMT" + tzStr);
      Calendar c = Calendar.getInstance();
      c.clear();
      c.setTimeZone(tz);
      c.set(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
      c.add(14, parts[6]);
      return c;
    } else {
      throw new UtilitiesException("Unable to convert datetime to UTC format:" + dateTime);
    }
  }
Exemple #2
1
  public TimezoneTest(String name) {
    super(name);

    TimeZone UTC = TimeZone.getTimeZone("UTC"); // +0000 always
    TimeZone GMT03 = TimeZone.getTimeZone("GMT+03"); // +0300 always
    TimeZone GMT05 = TimeZone.getTimeZone("GMT-05"); // -0500 always
    TimeZone GMT13 = TimeZone.getTimeZone("GMT+13"); // +1000 always

    cUTC = Calendar.getInstance(UTC);
    cGMT03 = Calendar.getInstance(GMT03);
    cGMT05 = Calendar.getInstance(GMT05);
    cGMT13 = Calendar.getInstance(GMT13);
  }
 @InitBinder("systemNotificationForm")
 protected void initBinder(WebDataBinder binder) {
   binder.setValidator(systemNotificationValidator);
   SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
   sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
   binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
   binder.registerCustomEditor(
       SystemNotificationType.class, new EnumEditor(SystemNotificationType.class));
   binder.registerCustomEditor(
       SystemNotificationSeverity.class, new EnumEditor(SystemNotificationSeverity.class));
   binder.registerCustomEditor(
       List.class,
       "types",
       new CustomCollectionEditor(List.class) {
         @Override
         protected Object convertElement(Object element) {
           SystemNotificationType type = null;
           if (element != null) {
             try {
               type = SystemNotificationType.valueOf((String) element);
             } catch (Exception ex) {
               log.error(
                   String.format(
                       "Error converting element to SystemNotificationType: %s", element),
                   ex);
             }
           }
           return type;
         }
       });
 }
Exemple #4
1
  void dateTest() throws RuntimeException {
    Locale locTH = new Locale("th", "TH", "TH");
    TimeZone tz = TimeZone.getTimeZone("PST");

    Calendar calGregorian = Calendar.getInstance(tz, Locale.US);
    calGregorian.clear();
    calGregorian.set(2002, 4, 1, 8, 30);
    final Date date = calGregorian.getTime();
    Calendar cal = Calendar.getInstance(tz, locTH);
    cal.clear();
    cal.setTime(date);

    final String strExpected =
        "\u0E27\u0E31\u0E19\u0E1E\u0E38\u0E18\u0E17\u0E35\u0E48\u0020\u0E51\u0020\u0E1E\u0E24\u0E29\u0E20\u0E32\u0E04\u0E21\u0020\u0E1E\u002E\u0E28\u002E\u0020\u0E52\u0E55\u0E54\u0E55\u002C\u0020\u0E58\u0020\u0E19\u0E32\u0E2C\u0E34\u0E01\u0E32\u0020\u0E53\u0E50\u0020\u0E19\u0E32\u0E17\u0E35\u0020\u0E50\u0E50\u0020\u0E27\u0E34\u0E19\u0E32\u0E17\u0E35";
    Date value = cal.getTime();

    // th_TH_TH test
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, locTH);
    df.setTimeZone(tz);
    String str = df.format(value);

    if (!strExpected.equals(str)) {
      throw new RuntimeException();
    }
  }
  public void testDateIssues() throws Exception {

    // test System.currentTimeMillis()
    long myApproximateTime = (long) 1.4412384e+12; // the current time of test execution
    long ct = System.currentTimeMillis();
    assertTrue(ct > myApproximateTime);

    // test date conversion and millisecond diffing
    DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yy");
    DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    DateFormat DATE_FORMAT2 = new SimpleDateFormat("dd/MM/yy");
    DATE_FORMAT2.setTimeZone(TimeZone.getTimeZone("Europe/Rome"));

    Date d1 =
        DATE_FORMAT.parse(
            "13/09/15"); // the same date comes before in Europe than in America/Pacific
    Date d2 = DATE_FORMAT2.parse("13/09/15");

    assertTrue(d2.compareTo(d1) < 0);
    assertTrue(d2.getTime() < d1.getTime());

    long diff = d1.getTime() - d2.getTime();
    long hoursDiff = TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);

    assertTrue(hoursDiff == 9L);

    // parse milliseconds, compare dates
    Date d3 = new Date(myApproximateTime);
    Date d4 = new Date(ct);

    assertTrue(d4.compareTo(d3) > 0);
  }
 public void test_toOffsetTime_variableOffset() {
   GregorianCalendar gcal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris"));
   gcal.set(2008, 0, 1, 0, 0, 0);
   gcal.set(Calendar.MILLISECOND, 0);
   for (int i = 0; i < 500; i++) {
     OffsetTime test = gcal.toOffsetTime();
     assertEquals(test.toLocalTime().toNanoOfDay(), 0);
     boolean isDST = TimeZone.getTimeZone("Europe/Paris").inDaylightTime(gcal.getTime());
     assertEquals(test.getOffset().getID(), isDST ? "+02:00" : "+01:00");
     gcal.add(Calendar.DATE, 1);
   }
 }
Exemple #7
0
 /** This code borrowed from Piesquared on irc.nexuswar.com */
 private TimeZone tZF(String search) {
   if (search.equals("")) return TimeZone.getTimeZone("GMT");
   search = search.toLowerCase();
   search = search.replace("+", "\\+");
   search = search.replace("*", "\\*");
   search = search.replace("?", "\\?");
   String[] zones = TimeZone.getAvailableIDs();
   for (int i = 0; i < zones.length; i++)
     if (zones[i].toLowerCase().equals(search)) return TimeZone.getTimeZone(zones[i]);
   for (int i = 0; i < zones.length; i++)
     if (zones[i].toLowerCase().matches(".*" + search + ".*"))
       return TimeZone.getTimeZone(zones[i]);
   return TimeZone.getTimeZone("GMT");
 }
 public void test_toOffsetDate_variableOffset() {
   GregorianCalendar gcal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris"));
   gcal.set(2008, 0, 1, 0, 0, 0);
   gcal.set(Calendar.MILLISECOND, 0);
   for (int i = 0; i < 500; i++) {
     OffsetDate test = gcal.toOffsetDate();
     assertEquals(test.getYear(), gcal.get(Calendar.YEAR));
     assertEquals(test.getMonthOfYear().getValue(), gcal.get(Calendar.MONTH) + 1);
     assertEquals(test.getDayOfMonth(), gcal.get(Calendar.DATE));
     assertEquals(test.getYear(), i < 366 ? 2008 : 2009);
     boolean isDST = TimeZone.getTimeZone("Europe/Paris").inDaylightTime(gcal.getTime());
     assertEquals(test.getOffset().getID(), isDST ? "+02:00" : "+01:00");
     gcal.add(Calendar.DATE, 1);
   }
 }
  public static BatchPoints create(String db, ZeitreihenDTO... zeitreihenDTOs)
      throws ParseException {
    BatchPoints batchPoints = BatchPoints.database(db).retentionPolicy("default").build();

    for (ZeitreihenDTO zeitreihenDTO : zeitreihenDTOs) {
      for (Long timestamp : timestamps(zeitreihenDTO)) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
        calendar.setTimeInMillis(timestamp);
        int monat = calendar.get(Calendar.MONTH) + 1;
        int jahr = calendar.get(Calendar.YEAR);

        batchPoints.point(
            Point.measurement("lastgang")
                .tag("zaehlpunktbezeichnung", zeitreihenDTO.zaehlpunktbezeichnung)
                .tag("commodity", zeitreihenDTO.commodity)
                .tag("zaehlverfahren", zeitreihenDTO.zaehlverfahren)
                .tag("monat", String.valueOf(monat))
                .tag("jahr", String.valueOf(jahr))
                .time(timestamp, TimeUnit.MILLISECONDS)
                .field("value", randomValue())
                .build());
      }
    }
    return batchPoints;
  }
  public static Collection<BatchPoints> create(
      int chunksize, String db, ZeitreihenDTO... zeitreihenDTOs) throws ParseException {
    List<Point> points = new ArrayList<>();
    for (ZeitreihenDTO zeitreihenDTO : zeitreihenDTOs) {
      for (Long timestamp : timestamps(zeitreihenDTO)) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
        calendar.setTimeInMillis(timestamp);
        int monat = calendar.get(Calendar.MONTH) + 1;
        int jahr = calendar.get(Calendar.YEAR);

        points.add(
            Point.measurement("lastgang")
                .tag("zaehlpunktbezeichnung", zeitreihenDTO.zaehlpunktbezeichnung)
                .tag("commodity", zeitreihenDTO.commodity)
                .tag("zaehlverfahren", zeitreihenDTO.zaehlverfahren)
                .tag("monat", String.valueOf(monat))
                .tag("jahr", String.valueOf(jahr))
                .time(timestamp, TimeUnit.MILLISECONDS)
                .field("value", randomValue())
                .build());
      }
    }

    Collection<BatchPoints> batchPoints = new ArrayList<>();
    Lists.partition(points, chunksize)
        .forEach(
            chunk -> {
              BatchPoints bp = BatchPoints.database(db).retentionPolicy("default").build();

              chunk.forEach(bp::point);
              batchPoints.add(bp);
            });
    return batchPoints;
  }
Exemple #11
0
  /**
   * Takes a packed-stream InputStream, and writes to a JarOutputStream. Internally the entire
   * buffer must be read, it may be more efficient to read the packed-stream to a file and pass the
   * File object, in the alternate method described below.
   *
   * <p>Closes its input but not its output. (The output can accumulate more elements.)
   *
   * @param in an InputStream.
   * @param out a JarOutputStream.
   * @exception IOException if an error is encountered.
   */
  public void unpack(InputStream in0, JarOutputStream 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"));
      final int verbose = _props.getInteger(Utils.DEBUG_VERBOSE);
      BufferedInputStream in = new BufferedInputStream(in0);
      if (Utils.isJarMagic(Utils.readMagic(in))) {
        if (verbose > 0) Utils.log.info("Copying unpacked JAR file...");
        Utils.copyJarFile(new JarInputStream(in), out);
      } else if (_props.getBoolean(Utils.DEBUG_DISABLE_NATIVE)) {
        (new DoUnpack()).run(in, out);
        in.close();
        Utils.markJarFile(out);
      } else {
        (new NativeUnpack(this)).run(in, out);
        in.close();
        Utils.markJarFile(out);
      }
    } finally {
      _nunp = null;
      Utils.currentInstance.set(null);
      if (tz != null) TimeZone.setDefault(tz);
    }
  }
 private void finalizePartitionsUpTo(String topic, Calendar calendar)
     throws IOException, ParseException, InterruptedException {
   NavigableSet<Calendar> partitionDates =
       getPartitions(topic).headSet(calendar, true).descendingSet();
   final String s3Prefix = "s3n://" + mConfig.getS3Bucket() + "/" + mConfig.getS3Path();
   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
   format.setTimeZone(TimeZone.getTimeZone("UTC"));
   for (Calendar partition : partitionDates) {
     String partitionStr = format.format(partition.getTime());
     String[] partitions = {"dt=" + partitionStr};
     LogFilePath logFilePath =
         new LogFilePath(
             s3Prefix, topic, partitions, mConfig.getGeneration(), 0, 0, mFileExtension);
     String logFileDir = logFilePath.getLogFileDir();
     assert FileUtil.exists(logFileDir) : "FileUtil.exists(" + logFileDir + ")";
     String successFilePath = logFileDir + "/_SUCCESS";
     if (FileUtil.exists(successFilePath)) {
       return;
     }
     try {
       mQuboleClient.addPartition(mConfig.getHivePrefix() + topic, "dt='" + partitionStr + "'");
     } catch (Exception e) {
       LOG.error("failed to finalize topic " + topic + " partition dt=" + partitionStr, e);
       continue;
     }
     LOG.info("touching file " + successFilePath);
     FileUtil.touch(successFilePath);
   }
 }
  /**
   * Creates the Hadoop authentication HTTP cookie.
   *
   * @param token authentication token for the cookie.
   * @param expires UNIX timestamp that indicates the expire date of the cookie. It has no effect if
   *     its value < 0.
   *     <p>XXX the following code duplicate some logic in Jetty / Servlet API, because of the fact
   *     that Hadoop is stuck at servlet 2.5 and jetty 6 right now.
   */
  public static void createAuthCookie(
      HttpServletResponse resp,
      String token,
      String domain,
      String path,
      long expires,
      boolean isSecure) {
    StringBuilder sb = new StringBuilder(AuthenticatedURL.AUTH_COOKIE).append("=");
    if (token != null && token.length() > 0) {
      sb.append("\"").append(token).append("\"");
    }
    sb.append("; Version=1");

    if (path != null) {
      sb.append("; Path=").append(path);
    }

    if (domain != null) {
      sb.append("; Domain=").append(domain);
    }

    if (expires >= 0) {
      Date date = new Date(expires);
      SimpleDateFormat df = new SimpleDateFormat("EEE, " + "dd-MMM-yyyy HH:mm:ss zzz");
      df.setTimeZone(TimeZone.getTimeZone("GMT"));
      sb.append("; Expires=").append(df.format(date));
    }

    if (isSecure) {
      sb.append("; Secure");
    }

    sb.append("; HttpOnly");
    resp.addHeader("Set-Cookie", sb.toString());
  }
 private Date getNewDate(int increment) throws ParseException {
   SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
   Calendar c = Calendar.getInstance();
   c.setTimeZone(TimeZone.getTimeZone("GMT"));
   c.setTime(sdf.parse(START_DATE));
   c.add(Calendar.DATE, increment);
   return c.getTime();
 }
 @Override
 public String toString(long timestamp, String timezone) {
   // Por enquanto, o fuso horário deve ser UTC:
   assert timezone.equals("UTC");
   DateFormat formatter = new SimpleDateFormat(DEFAULT_FORMAT);
   formatter.setTimeZone(TimeZone.getTimeZone(timezone));
   return formatter.format(new Date(timestamp * 1000)) + " " + timezone;
 }
 @Override
 public void setUp() {
   Calendar cal = new GregorianCalendar(2007, 8 - 1, 13, 19, 51, 23);
   cal.setTimeZone(TimeZone.getTimeZone("GMT"));
   cal.set(Calendar.MILLISECOND, 0);
   date = cal.getTime();
   df = new ISO8601DateFormat();
 }
Exemple #17
0
 public static String getLocalDayOfWeek(long gmtTime) {
   // local
   Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
   cal.setTime(new Date(Util.gmtTimeToLocalTime(gmtTime) * 1000));
   String[] days = {
     "", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"
   };
   return JLocale.getString(days[cal.get(Calendar.DAY_OF_WEEK)]);
 }
Exemple #18
0
 /**
  * Parse the given {@code timeZoneString} value into a {@link TimeZone}.
  *
  * @param timeZoneString the time zone String, following {@link TimeZone#getTimeZone(String)} but
  *     throwing {@link IllegalArgumentException} in case of an invalid time zone specification
  * @return a corresponding {@link TimeZone} instance
  * @throws IllegalArgumentException in case of an invalid time zone specification
  */
 public static TimeZone parseTimeZoneString(String timeZoneString) {
   TimeZone timeZone = TimeZone.getTimeZone(timeZoneString);
   if ("GMT".equals(timeZone.getID()) && !timeZoneString.startsWith("GMT")) {
     // We don't want that GMT fallback...
     throw new IllegalArgumentException(
         "Invalid time zone specification '" + timeZoneString + "'");
   }
   return timeZone;
 }
Exemple #19
0
  private void updateClientTimeZone(String elementName) {
    if (timeZone != TimeZoneVisibility.SELECT) return;

    String id = request.getParameter(elementName + "$timezone");

    TimeZone tz = TimeZone.getTimeZone(id);

    timeZoneTracker.setClientTimeZone(tz);
  }
  private XMLGregorianCalendar getTimeToXmlTime(long lastModified)
      throws DatatypeConfigurationException {

    GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("UTC"));

    gc.setTime(new Date(lastModified));

    XMLGregorianCalendar xmlTime = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
    return xmlTime;
  }
 /**
  * Convert date to long keeping the timezone valued date. When asking the time of a Date object
  * java return the milliseconds from the begin of counting. "Returns the number of milliseconds
  * since January 1, 1970, 00:00:00 GMT represented by this Date object."
  *
  * <p>This can be a problem when accepting JavaSript to create a JavaScript Date object not
  * knowing the time zone and ..
  */
 public Long convertDateToMilliseconds(Date date) {
   if (date == null) return null;
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date);
   Calendar calendarConverted = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.ENGLISH);
   calendarConverted.clear();
   calendarConverted.set(
       calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
   return calendarConverted.getTimeInMillis();
 }
 public void test_toLocalTime_variableOffset() {
   GregorianCalendar gcal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris"));
   gcal.set(2008, 0, 1, 0, 0, 0);
   gcal.set(Calendar.MILLISECOND, 0);
   for (int i = 0; i < 500; i++) {
     LocalTime test = gcal.toLocalTime();
     assertEquals(test.toNanoOfDay(), 0);
     gcal.add(Calendar.DATE, 1);
   }
 }
 public void test_toLocalTime_endOfDay() {
   GregorianCalendar gcal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
   gcal.set(2008, 0, 1, 23, 59, 59);
   gcal.set(Calendar.MILLISECOND, 0);
   for (int i = 0; i < 500; i++) {
     LocalTime test = gcal.toLocalTime();
     assertEquals(test.toNanoOfDay(), (24L * 60L * 60L - 1L) * 1000000000L);
     gcal.add(Calendar.DATE, 1);
   }
 }
  @Test
  public void should_dsl_select_slice_async() throws Exception {
    // Given
    final Map<String, Object> values = new HashMap<>();
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    values.put("id", id);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    final Date date1 = dateFormat.parse("2015-10-01 00:00:00 GMT");
    final Date date9 = dateFormat.parse("2015-10-09 00:00:00 GMT");
    values.put("date1", "'2015-10-01 00:00:00+0000'");
    values.put("date2", "'2015-10-02 00:00:00+0000'");
    values.put("date3", "'2015-10-03 00:00:00+0000'");
    values.put("date4", "'2015-10-04 00:00:00+0000'");
    values.put("date5", "'2015-10-05 00:00:00+0000'");
    values.put("date6", "'2015-10-06 00:00:00+0000'");
    values.put("date7", "'2015-10-07 00:00:00+0000'");
    values.put("date8", "'2015-10-08 00:00:00+0000'");
    values.put("date9", "'2015-10-09 00:00:00+0000'");
    scriptExecutor.executeScriptTemplate("SimpleEntity/insert_many_rows.cql", values);

    final CountDownLatch latch = new CountDownLatch(1);
    final CassandraLogAsserter logAsserter = new CassandraLogAsserter();
    logAsserter.prepareLogLevel(ASYNC_LOGGER_STRING, "%msg - [%thread]%n");

    // When
    final CompletableFuture<List<SimpleEntity>> future =
        manager
            .dsl()
            .select()
            .consistencyList()
            .simpleSet()
            .simpleMap()
            .value()
            .simpleMap()
            .fromBaseTable()
            .where()
            .id()
            .Eq(id)
            .date()
            .Gte_And_Lt(date1, date9)
            .withResultSetAsyncListener(
                rs -> {
                  LOGGER.info(CALLED);
                  latch.countDown();
                  return rs;
                })
            .withTracing()
            .getListAsync();

    // Then
    latch.await();
    assertThat(future.get()).hasSize(8);
    logAsserter.assertContains("Called - [achilles-default-executor");
  }
  private void init() throws IOException {
    members = new StructureMembers("stationObs");

    // used to convert from adde format
    calendar = new GregorianCalendar();
    calendar.setTimeZone(TimeZone.getTimeZone("GMT"));

    // time unit
    timeUnit = DateUnit.getUnixDateUnit();

    try {
      AddePointDataReader reader = callAdde(addeURL);

      String[] params = reader.getParams();
      String[] units = reader.getUnits();
      int[] scales = reader.getScales();
      scaleFactor = new double[params.length];

      if (debugHead) System.out.println(" Param  Unit Scale");
      for (int paramNo = 0; paramNo < params.length; paramNo++) {
        // memberNames.add( params[i]);

        if (debugHead)
          System.out.println(" " + params[paramNo] + " " + units[paramNo] + " " + scales[paramNo]);
        if (scales[paramNo] != 0)
          scaleFactor[paramNo] = 1.0 / Math.pow(10.0, (double) scales[paramNo]);

        DataType dt = null;
        if ("CHAR".equals(units[paramNo])) dt = DataType.STRING;
        else if (scaleFactor[paramNo] == 0) dt = DataType.INT;
        else dt = DataType.DOUBLE;

        String unitString = null;
        if ((units[paramNo] != null) && (units[paramNo].length() > 0))
          unitString = visad.jmet.MetUnits.makeSymbol(units[paramNo]);

        AddeTypedDataVariable tdv = new AddeTypedDataVariable(params[paramNo], unitString, dt);
        dataVariables.add(tdv);
        StructureMembers.Member m =
            members.addMember(
                tdv.getShortName(),
                tdv.getDescription(),
                tdv.getUnitsString(),
                tdv.getDataType(),
                tdv.getShape());
        m.setDataParam(paramNo);
        members.addMember(m);
      }

    } catch (AddeException e) {
      e.printStackTrace();
      throw new IOException(e.getMessage());
    }
  }
Exemple #26
0
  static {
    // DATE_FORMATS
    DateFormat fmt;

    // XEP-0091
    DATE_FORMATS.add(DelayInformation.XEP_0091_UTC_FORMAT);
    fmt = new SimpleDateFormat("yyyyMd'T'HH:mm:ss'Z'");
    fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    DATE_FORMATS.add(fmt);

    // XEP-0082
    fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    DATE_FORMATS.add(fmt);
    fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    DATE_FORMATS.add(fmt);
    DATE_FORMATS.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
    DATE_FORMATS.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
  }
 public void test_toOffsetTime_fixedOffset() {
   GregorianCalendar gcal = new GregorianCalendar(TimeZone.getTimeZone("GMT+12:00"));
   gcal.set(2008, 0, 1, 0, 0, 0);
   gcal.set(Calendar.MILLISECOND, 0);
   for (int i = 0; i < 500; i++) {
     OffsetTime test = gcal.toOffsetTime();
     assertEquals(test.toLocalTime().toNanoOfDay(), 0);
     assertEquals(test.getOffset().getID(), "+12:00");
     gcal.add(Calendar.DATE, 1);
   }
 }
  // \u65e5\u4ed8\u30d5\u30a9\u30fc\u30de\u30c3\u30c8\u306e\u53d6\u5f97
  public SimpleDateFormat getDateFormat_ISO8601() {

    // ISO 8601(UTC)\u3000\u306e\u30d5\u30a9\u30fc\u30de\u30c3\u30c8\u3092\u4f5c\u6210
    String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.000000'Z'";
    // String timeZoneName = "UTC";
    String timeZoneName = "JST";
    SimpleDateFormat sdfIso8601ExtendedFormatUtc = new SimpleDateFormat(dateFormat);
    sdfIso8601ExtendedFormatUtc.setTimeZone(TimeZone.getTimeZone(timeZoneName));

    return sdfIso8601ExtendedFormatUtc;
  }
Exemple #29
0
  static Date parseDate(String s) {
    Calendar c = new GregorianCalendar(TimeZone.getTimeZone("UTC"));

    int year = Integer.parseInt(s.substring(0, 4));
    int month = Integer.parseInt(s.substring(4, 6)) - 1;
    int date = Integer.parseInt(s.substring(6, 8));
    int hour = Integer.parseInt(s.substring(8, 10));
    int minute = Integer.parseInt(s.substring(10, 12));
    int second = Integer.parseInt(s.substring(12, 14));
    c.set(year, month, date, hour, minute, second);

    return c.getTime();
  }
  /**
   * Converts a Date into a formatted string.
   *
   * @param date The Date to convert.
   * @return The formatted string.
   */
  public static String format(Date date) {
    Calendar c = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    StringBuffer sb = new StringBuffer();

    c.setTime(date);
    sb.append(w4.format(c.get(Calendar.YEAR)));
    sb.append(w2.format(c.get(Calendar.MONTH) + 1));
    sb.append(w2.format(c.get(Calendar.DAY_OF_MONTH)));
    sb.append(w2.format(c.get(Calendar.HOUR_OF_DAY)));
    sb.append(w2.format(c.get(Calendar.MINUTE)));
    sb.append(w2.format(c.get(Calendar.SECOND)));
    return sb.toString();
  }