Exemplo n.º 1
0
  /**
   * Converts this <code>Date</code> object to a <code>String</code> of the form:
   *
   * <blockquote>
   *
   * <pre>
   * dow mon dd hh:mm:ss zzz yyyy</pre>
   *
   * </blockquote>
   *
   * where:
   *
   * <ul>
   *   <li><tt>dow</tt> is the day of the week (<tt>Sun, Mon, Tue, Wed, Thu, Fri, Sat</tt>).
   *   <li><tt>mon</tt> is the month (<tt>Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov,
   *       Dec</tt>).
   *   <li><tt>dd</tt> is the day of the month (<tt>01</tt> through <tt>31</tt>), as two decimal
   *       digits.
   *   <li><tt>hh</tt> is the hour of the day (<tt>00</tt> through <tt>23</tt>), as two decimal
   *       digits.
   *   <li><tt>mm</tt> is the minute within the hour (<tt>00</tt> through <tt>59</tt>), as two
   *       decimal digits.
   *   <li><tt>ss</tt> is the second within the minute (<tt>00</tt> through <tt>61</tt>, as two
   *       decimal digits.
   *   <li><tt>zzz</tt> is the time zone (and may reflect daylight savings time). If time zone
   *       information is not available, then <tt>zzz</tt> is empty - that is, it consists of no
   *       characters at all.
   *   <li><tt>yyyy</tt> is the year, as four decimal digits.
   * </ul>
   *
   * @return a string representation of this date.
   */
  public static String toString(Calendar calendar) {
    // Printing in the absence of a Calendar
    // implementation class is not supported
    if (calendar == null) {
      return "Thu Jan 01 00:00:00 UTC 1970";
    }

    int dow = calendar.get(Calendar.DAY_OF_WEEK);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int hour_of_day = calendar.get(Calendar.HOUR_OF_DAY);
    int minute = calendar.get(Calendar.MINUTE);
    int seconds = calendar.get(Calendar.SECOND);
    int year = calendar.get(Calendar.YEAR);

    String yr = Integer.toString(year);

    TimeZone zone = calendar.getTimeZone();
    String zoneID = zone.getID();
    if (zoneID == null) zoneID = "";

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

    sb.append(days[dow - 1]).append(' ');
    sb.append(months[month]).append(' ');
    appendTwoDigits(sb, day).append(' ');
    appendTwoDigits(sb, hour_of_day).append(':');
    appendTwoDigits(sb, minute).append(':');
    appendTwoDigits(sb, seconds).append(' ');
    if (zoneID.length() > 0) sb.append(zoneID).append(' ');
    appendFourDigits(sb, year);

    return sb.toString();
  }