tl;dr
org.threeten.bp.Year.parse( // Parse a string into a `Year` object. Using the back-port of *java.time* classes found in the *ThreeTen-Backport* project, further adapted for earlier Android in the *ThreeTenABP* project.
"1961" // String input representing a year.
)
.until( // Calculate elapsed time.
Year.now( // Get the current date’s year as a `Year` object rather than a mere integer number.
ZoneId.of( "Africa/Tunis" ) // Get the current year as seen in the wall-clock time used by the people of a particular region (time zone). For any given moment, the date varies around the globe by zone.
) ,
ChronoUnit.YEARS // Specify the granularity of the elapsed time using `ChronoUnit` enum.
) // Return a `long`.
57
Year
How to get current year in Android (min API version 15)
There’s a class for that!
Year
shown in Java syntax (I don’t know Kotlin, yet)
Year.now()
Better to specify explicitly the desired/expected time zone rather than rely implicitly on your JVM’s current default time zone.
Year.now(
ZoneId.of( "Europe/Lisbon" )
)
Pass this Year
object around your code rather than mere integer numbers. This gives you type-safety, and makes your code more self-documenting. When you do need a number, call Year.getValue
.
Year y = Year.now( ZoneId.systemDefault() ) ;
int yearNumber = y.getValue() ;
The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes. Avoid Calendar
, Date
, SimpleDateFormat
like the Plague.
For Java 6 & 7, see the ThreeTen-Backport project. For earlier Android, see the ThreeTenABP project.
Age
To calculate the age, parse your string input.
String input = "1961" ;
Year birthYear = Year.parse( input ) ;
Do the math. Specify a TemporalUnit
(ChronoUnit
) for the granularity of result.
Year now = Year.now( ZoneId.systemDefault() ) ; // 2018 today.
long years = birthYear.until( now , ChronoUnit.YEARS ) ;
57
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
.
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.
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?