Exemplo n.º 1
0
  /**
   * Converts this <code>Date</code> object to a <code>String</code>. The output format is as
   * follows:
   *
   * <blockquote>
   *
   * <pre>yyyy MM dd hh mm ss +zzzz</pre>
   *
   * </blockquote>
   *
   * where:
   *
   * <ul>
   *   <li>
   *   <dd>yyyy is the year, as four decimal digits. Year values larger than
   *   <dd>9999 will be truncated to
   *   <dd>9999.
   *   <li>
   *   <dd>MM is the month (
   *   <dd>01 through
   *   <dd>12), as two decimal digits.
   *   <li>
   *   <dd>dd is the day of the month (
   *   <dd>01 through
   *   <dd>31), as two decimal digits.
   *   <li>
   *   <dd>hh is the hour of the day (
   *   <dd>00 through
   *   <dd>23), as two decimal digits.
   *   <li>
   *   <dd>mm is the minute within the hour (
   *   <dd>00 through
   *   <dd>59), as two decimal digits.
   *   <li>
   *   <dd>ss is the second within the minute (
   *   <dd>00 through
   *   <dd>59), as two decimal digits.
   *   <li>
   *   <dd>zzzz is the time zone offset in hours and minutes (four decimal digits
   *   <dd>"hhmm") relative to GMT, preceded by a "+" or "-" character (
   *   <dd>-1200 through
   *   <dd>+1200). For instance, Pacific Standard Time zone is printed as
   *   <dd>-0800. GMT is printed as
   *   <dd>+0000.
   * </ul>
   *
   * @return a string representation of this date.
   */
  public static String toISO8601String(Calendar calendar) {
    // Printing in the absence of a Calendar
    // implementation class is not supported
    if (calendar == null) {
      return "0000 00 00 00 00 00 +0000";
    }

    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH) + 1;
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int hour_of_day = calendar.get(Calendar.HOUR_OF_DAY);
    int hour = calendar.get(Calendar.HOUR);
    int minute = calendar.get(Calendar.MINUTE);
    int seconds = calendar.get(Calendar.SECOND);

    String yr = Integer.toString(year);

    // The total size of the string buffer
    // yr.length+1+2+1+2+1+2+1+2+1+2+1+5 = 25 + yr.length
    StringBuffer sb = new StringBuffer(25 + yr.length());

    appendFourDigits(sb, year).append(' ');
    appendTwoDigits(sb, month).append(' ');
    appendTwoDigits(sb, day).append(' ');
    appendTwoDigits(sb, hour_of_day).append(' ');
    appendTwoDigits(sb, minute).append(' ');
    appendTwoDigits(sb, seconds).append(' ');

    // TimeZone offset is represented in milliseconds.
    // Convert the offset to minutes:
    TimeZone t = calendar.getTimeZone();
    int zoneOffsetInMinutes = t.getRawOffset() / 1000 / 60;

    if (zoneOffsetInMinutes < 0) {
      zoneOffsetInMinutes = Math.abs(zoneOffsetInMinutes);
      sb.append('-');
    } else {
      sb.append('+');
    }

    int zoneHours = zoneOffsetInMinutes / 60;
    int zoneMinutes = zoneOffsetInMinutes % 60;

    appendTwoDigits(sb, zoneHours);
    appendTwoDigits(sb, zoneMinutes);

    return sb.toString();
  }