tl;dr
LocalDateTime // Represent a date with time-of-day, but lacking the context of a time zone or offset-from-UTC. So, this is *not* a moment.
.parse(
"15-2-21 11:34" ,
DateTimeFormatter.ofPattern( "d-M-uu HH:mm" )
) // Returns a `LocalDateTime` object.
.atZone( // Determine a moment by placing the date & time within the context of a time zone.
ZoneId.of( "Africa/Tunis" ) // The time zone by which to interpret the input string. Do this only if you are *certain* of the intended zone.
) // Returns a `ZonedDateTime` object.
.toInstant() // Same moment, as viewed through an offset of zero hours-minutes-seconds from UTC.
.isAfter( // Compare two moments.
Instant.now() // Capture current moment as seen through an offset of zero hours-minutes-seconds from UTC.
) // Returns a boolean.
Details
Besides the solution posted by Akshar, you have other problems.
Your example input has a single digit for month, but your formatting codes use two MM
characters which means you expect always two digits with padding zero if needed. Use one M
and one d
if you do not expect padding zero.
You are using classes that represent a date-time in the context of a time zone or offset. But your input lacks any indicator of a time zone or offset.
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes.
String input = "15-2-21 11:34" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d-M-uu HH:mm" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
You are trying to compare that date-time with the current moment. That does not make sense, as that text input does not tell us the time zone in which we are expected to perceive that date and time. Is that 11:30 AM in Tokyo Japan, 11:30 AM in Toulouse France, or 11:30 AM in Toledo Ohio US? Those would be three different moment, several hours apart.
If you know for certain the intended time zone, apply a ZoneId
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
if( zdt.isBefore( now ) ) { … }