Javaのカレンダーに誤った前日

SMPH:

私が使用して、前日取得したいCalenderJavaで。私は以下のコードを使用しています。

Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -1);
now.add(Calendar.MONTH, -2);

myDate = now.get(Calendar.MONTH) + "/" + now.get(Calendar.DATE) + "/" + now.get(Calendar.YEAR);

System.out.println(myDate);

出力: 2/31/2020

問題は、すべての時間を動作しません上記です。現在の日付がある場合は、上記のとおり03/01/2020、あなたは上記の結果を取得します。しかし、2月は持つことができません31内のオプションがありCalendar、これを処理するために、libには?

私はフォーマットすると、以下の使用している場合、それは完全に異なる値を与えます。

Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -1);
now.add(Calendar.MONTH, -2);
SimpleDateFormat df = new SimpleDateFormat("MM/DD/YYYY");
String myDate= df.format(now.getTime());

System.out.println(myDate);

出力: 03/91/2020

アンドロニカス:

あなたの日付の書式は、あなたがすることを意図したものではありません。前の日(昨日)を取得するには、以下をお試しください:

Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -1);
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String MyDate= df.format(now.getTime());

System.out.println(MyDate);

よると、文書 "YYYY"週年で、"DD"年にダです。

PS:Javaで大会変数名で小文字を書かれています。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=18831&siteId=1