質問

はい、プログラムに日付を出力します:2009年1月1日

しかし、これは印刷されるものです:

2009年1月1日木曜日00:00:00 EST 2009

このコードから

GregorianCalendar startDate = new GregorianCalendar(2009, Calendar.JANUARY, 1);
public void setStart()
{
    startDate.setLenient(false);
    Date date = new Date(startDate.getTimeInMillis());
    System.out.println(date);
}

2009年1月1日のみを印刷するように変更するにはどうすればよいですか

役に立ちましたか?

解決

SimpleDateFormat を使用する

GregorianCalendar startDate = new GregorianCalendar(2009, Calendar.JANUARY, 1);
public void setStart() {
  startDate.setLenient(false); 
  DateFormat df = new SimpleDateFormat("d/M/yyyy");
  df.format(startDate.getDate());
}

完全にコンテンツを(正しく)印刷する toString()メソッドを暗黙的に呼び出しています。

ところで、あなたがしているように日付を構築する必要はありません。 Calendar getDate()を呼び出すと、 Date オブジェクトが返されます。

他のヒント

現在、 Date.toString() メソッドが呼び出され、String 表現を表示します。 /docs/api/java/util/GregorianCalendar.html "rel =" nofollow noreferrer "> GregorianCalendar インスタンス。

行う必要があるのは、を作成することです DateFormat は、必要な String 表現を生成します。 DateFormat オブジェクトを使用すると、 format メソッド。

目的を達成する最も簡単な方法は、 SimpleDateFormat クラス。フォーマット文字列を取得するコンストラクタにより、 Date を目的の形式で出力します。

Calendar calendar = new GregorianCalendar(2009, Calendar.JANUARY, 1);
DateFormat df = new SimpleDateFormat("M/d/yyyy");
System.out.println(df.format(calendar.getTime()));

出力

1/1/2009
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top