次のような2つの日付があるとします。ジョーダのDateTimeの秒とミリ秒の瞬間を無視して日付を比較する
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTime firstDate = formatter.parseDateTime("16-Feb-2012 12:03:45");
DateTime secondDate = formatter.parseDateTime("17-Feb-2013 12:03:45");
私はfirstDate
が早く、またはそれ以降secondDate
に等しいかどうかを確認するために、これらの2つの日付を比較したいです。
私は以下のことを試すことができます。
System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.isBefore(secondDate));
System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.isAfter(secondDate));
System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.equals(secondDate));
このコードによって生成されるものは、私が欲しいものです。
次の出力が生成されます。
firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = true
firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = false
firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = false
私は秒、これらの日付のミリ秒の部分を無視する必要があります。私はwithSecondOfMinute(0)
とwithMillis(0)
メソッドを以下のように使用しようとしました。
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTime firstDate = formatter.parseDateTime("16-Feb-2012 12:03:45").withSecondOfMinute(0).withMillis(0);
DateTime secondDate = formatter.parseDateTime("17-Feb-2013 12:03:45").withSecondOfMinute(0).withMillis(0);
ただし、次のような結果が得られました。
firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = false
firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = false
firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = true
withSecondOfMinute()
の方法のドキュメントが説明しています。
分秒フィールド が更新されたこの日時のコピーを返します。 DateTimeは不変なので、設定されたメソッドはありません。代わりに、 このメソッドは、秒の値が である新しいインスタンスを返します。
withMillis()
のドキュメントには、次のように記載されています。
ミリ秒単位でこのdatetimeのコピーを返します。返された オブジェクトは、新しいインスタンスまたはこれになります。ミリ秒だけが に変更され、年表とタイムゾーンが維持されます。
DateTimeComparator.getDateOnlyInstance()
を使用すると、日付部分を完全に無視して日付を比較することは、おおよそ次のようになります。 (この場合、秒、ミリ秒)DateTime
内の特定の瞬間を無視して二つの日付を比較する方法
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)==0){}
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)<0){}
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)>0){}
?
ありがとうございました。完了! – Tiny
@Tiny。あなたは大歓迎です:) –