Hey I have Iso Format date. I want to compare with current date. If date is equal to current date, I need the time of given Iso date and otherwise i need date.
val date = "2021-10-01T18:39:10.0492422 01:00"
How to compare today’s date with this value. If date is match i need time in HH:MM otherwise dd MMM YYYY format.
Important thing my minSdkVersion 21
CodePudding user response:
tl;dr
Java syntax, as I don’t know Kotlin:
LocalDate
.now( ZoneId.of( "America/Edmonton" ) )
.isEqual(
OffsetDateTime
.parse( "2021-10-01T18:39:10.0492422 01:00" )
.atZoneSameInstant( ZoneId.of( "America/Edmonton" ) )
.toLocalDate()
)
As for generating text from java.time objects in specific formats using DateTimeFormatter
and DateTimeFormatterBuilder
classes, that has been covered many many times already. Search to learn more.
Details
The latest Android tooling brings much of the java.time functionality built into Android 26 to earlier Android via “API de-sugaring”.
In Java syntax…
Parse your input as a OffsetDateTime
.
OffsetDateTime odt = OffsetDateTime.parse( "2021-10-01T18:39:10.0492422 01:00" ) ;
Adjust to the time zone by which you perceive “today’s date”.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
Get today’s date as seen in your target time zone, a LocalDate
.
LocalDate today = LocalDate.now( z ) ;
Compare to the date of our input as seen in the same time zone.
boolean sameDate = today.isEqual( zdt.toLocalDate() ) ;
As seen above, you must provide a time zone. For any given moment, the date varies around the globe by time zone. Right now is “tomorrow” in Tokyo Japan while simultaneously “yesterday” in Toledo Ohio US. So to ask “what is the date today?”, you must also specify where, that is, by what time zone do you want to perceive the current date.