tl;dr
For Android before 26, use the ThreeTen-ABP library.
Avoid legacy date-time classes
The old date-time classes such as Calendar
and Date
are terrible, really, awful wretched classes. They are laden with bad design decisions and hacks, built by people who did not understand date-time handling. Avoid them. They were entirely supplanted by the java.time classes with the adoption of JSR 310 for a reason – actually, many reasons.
Avoid these legacy classes. Use only java.time classes.
ThreeTen-Backport library
For Java 6 and Java 7, most of the java.time functionality is back-ported in the ThreeTen-Backport project.
ThreeTen-ABP
That back-port is further adapted to earlier Android (<26) in the ThreeTen-ABP project.
I urge you to add this library to your project so you can avoid ever using the tragic legacy classes.
Conversion
Where you need to interface with old code not yet updated to java.time, convert back-and-forth between legacy and modern.
In Java 8 and later, convert by calling the new to…
and from…
methods found on the old classes.
In the back-port, convert using the to…
conversion methods found on the org.threeten.bp.DateTimeUtils
class.
Elapsed time
Your Question talks about calculating elapsed time.
To count years, months, and days, use Period
.
To count days (24-hour chunks of time unrelated to the calendar), hours, minutes, seconds, and fractional second, use Duration
.
Search Stack Overflow for more info. These classes have been covered many time already.
About java.time
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
2019-02-23T10:21:04.791797+01:00
, thenOffsetDateTime
is a still better match for parsing. The question is whether the string has a time zone in it (like Pacific/Pitcairn or ACWST) or only an offset (like+01:00
). – Uniocular