I have an issue with date/time age calculations on Android Studio. I have used calander instance and it seemed to work for the most part but every now and then it seems to be Inaccurate.
I switched to LocalDate which looks way cleaner but, as far as I can tell through my research is only supported by API 26 and higher. I think Joda Time has the same issue.
My question is this: What is the best method to calculate the elapsed time between two dates that is the most accurate (factoring in leap years, months with different number of days, etc) and is supported by lower API versions (ie 17 and up)?
I have been researching and it appears that the answer may be the basic calander instance but then I come back to reliability and accuracy issue. Any input would be greatly appreciated.
Use the ThreeTenABP library in work with earlier versions of Android.
Period.between(
LocalDate.of( 2017 , Month.JUNE , 23 ) ,
LocalDate.now( ZoneId.of( “Europe/Paris” ) )
)
The original date-time classes bundled with the earliest versions of Java were well-intentioned but are an awful ugly confusing mess. Always avoid Date
, Calendar
, etc.
Joda-Time was an amazing industry-leading effort to make a serious robust date-time framework. Its principal author, Stephen Colebourne, went on to use the lessons learned there to produce its successor, the java.time classes built into Java 8 & 9, defined by JSR 310. The Joda-Time project is now in maintenance mode, and migration to java.time is advised.
Much of the java.time functionality is back-ported to Java 6 and Java 7 in the ThreeTen-Backport project. That project includes a utility class for converting to/from the legacy types so your new code may interoperate with old existing code. Further adapted for earlier Android in the ThreeTenABP project.
For example, on the Java platform you would call:
java.time.LocalDate localDate = java.time.LocalDate.of( 2018 , 1 , 23 ) ; // January 23rd, 2018.
…whereas on early Android using the ThreeTen-Backport/ThreeTenABP projects you would call:
org.threeten.bp.LocalDate localDate = org.threeten.bp.LocalDate.of( 2018 , 1 , 23 ) ; // January 23rd, 2018.
To calculate elapsed time as a span of time unattached to the timeline, use either:
Period
for years, months, daysDuration
for hours, minutes, seconds, and fractional second in nanoseconds. More simply put…
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?