[英]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.