2

java.util.Dateの使い方についてお聞きしたいです。ここに私のサンプルクラスがあります

         public class DateConverter {
           public static void main(String[] args) {
                  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
                  Date today = new Date();
                  String dateAsString_format = simpleDateFormat.format(today);
                  System.out.println("Formatted Date String (String datatype): " + dateAsString_format);
                  Date parsedDate = null;
                  try {
                      parsedDate = simpleDateFormat.parse(dateAsString_format);
                  } catch (ParseException e) {
                      e.printStackTrace();
                  }
                  System.out.println("Parse Date (Date datatype): " + parsedDate);
               }
            }

私の出力は

         Formatted Date String (String datatype): 06/10/2013
         Parse Date (Date datatype): Sun Oct 06 00:00:00 MMT 2013

しかし、私は次の出力を得たいと思っています

         Formatted Date String (String datatype): 06/10/2013
         Parse Date (Date datatype): 06/10/2013

特定の形式で Date オブジェクトを取得することは可能ですか?

4

2 に答える 2

4

はい、次の行に沿ってDate、フォーマットフィールドとオーバーライドメソッドを追加して拡張しますtoString

public class DateWithFormat extends Date {
   String format; // Assign as appropriate
   public String toString() {
     return new SimpleDateFormat(format).format(this));
   } 
}
于 2013-10-06T10:43:24.817 に答える
3

特定の形式で Date オブジェクトを取得することは可能ですか?

いいえDate、形式はありません。エポックからのミリ秒数を表します。SimpleDateFormatすでに行った を使用して、フォーマットされた文字列のみを取得します。

印刷DateはオーバーライドされたDate#toString()メソッドを呼び出します。このメソッドは、everyDateが印刷される既定の形式を使用します。

Date#toString()ソースは次のようになります。

public String toString() {
    // "EEE MMM dd HH:mm:ss zzz yyyy";
    BaseCalendar.Date date = normalize();
    StringBuilder sb = new StringBuilder(28);
    int index = date.getDayOfWeek();
    if (index == gcal.SUNDAY) {
        index = 8;
    }
    ....  // some more code
}

したがって、使用される形式は"EEE MMM dd HH:mm:ss zzz yyyy"

于 2013-10-06T09:49:44.183 に答える