Reputation: 21
I want to compare two date one is to take as current date and another one is static date that is from local variable. I want to compare date and month only i have written one program can anyone confirm is it right or not ?
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.
Upvotes: 1
Views: 879
Reputation: 339845
MonthDay
.of( Month.OCTOBER , 1 )
.isAfter(
MonthDay
.parse(
"27/09" ,
DateTimeFormatter.ofPattern( "dd/MM" )
)
)
Run this code at Ideone.com.
true
java.time.MonthDay
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
For a day of month, use MonthDay
class.
MonthDay md = MonthDay.of( 9 , 27 ) ;
For exchanging date-time values as text, ask the publisher of your data to use only standard ISO 8601 formats. For month-day, that format is --MM-DD
.
String output = md.toString() ;
--09-27
If you must accept non-standard input, define a formatting pattern with DateTimeFormatter
class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM" ) ;
Parse your input.
String input = "27/09" ;
MonthDay sept27 = MonthDay.parse( input , f ) ;
sept27.toString(): --09-27
See this code run live at Ideone.com.
You can compare MonthDay
objects by using their methods isBefore
, equals
, and isAfter
.
If you want the current year-month, you need to a time zone. For any given moment, the date varies around the globe by time zone. So near the start/end of a month, it might be “next” month in Tokyo Japan while simultaneously “previous” month in Toledo Ohio US.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
MonthDay currentYearMonth = MonthDay.now( z ) ;
Upvotes: 6