[英]How to compare First Date should be greater than second date in java?
我想比較兩個日期,一個是當前日期,另一個是來自局部變量的 static 日期。 我只想比較日期和月份,我只寫了一個程序,誰能確認它是否正確?
String str="27/09";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM");
LocalDateTime now = LocalDateTime.now();
String date1=dtf.format(now);
System.out.println("fist date Date 1\t"+date1);
SimpleDateFormat sdformat = new SimpleDateFormat("dd/MM");
Date d1 = sdformat.parse(str);
String date2=sdformat.format(d1);
System.out.println("second date Date2 \t"+date2);
int result = date1.compareTo(date2);
if (result < 0) {
System.out.println("Date1 is before Date2");
}```
LOCALDATE>STATICVARIABLE DATE this is condition and want to compare date and month only.
您正在使用可怕的日期時間類,這些類在幾年前被 JSR 310 中定義的現代java.time類所取代。
對於一個月中的某一天,請使用MonthDay
class。
MonthDay md = MonthDay.of( 9 , 27 ) ;
要將日期時間值交換為文本,請要求您的數據發布者僅使用標准ISO 8601格式。 對於月日,該格式為--MM-DD
。 9 月 27 日將是--09-27
。
String output = md.toString() ;
如果您必須接受非標准輸入,請使用DateTimeFormatter
class 定義格式模式。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM" ) ;
解析您的輸入。
String input = "27/09" ;
MonthDay sept27 = MonthDay.parse( input , f ) ;
sept27.toString(): --09-27
您可以使用MonthDay
對象的方法isBefore
、 equals
和isAfter
來比較它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.