fun calculateAge(dateString: String): String {
val dateFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z")
dateFormat.timeZone = TimeZone.getTimeZone("GMT")
val inputDate = dateFormat.parse(dateString)
val currentCalendar = Calendar.getInstance()
val inputCalendar = Calendar.getInstance()
inputCalendar.time = inputDate
val years = currentCalendar.get(Calendar.YEAR) - inputCalendar.get(Calendar.YEAR)
val months = currentCalendar.get(Calendar.MONTH) - inputCalendar.get(Calendar.MONTH)
val days = currentCalendar.get(Calendar.DAY_OF_MONTH) - inputCalendar.get(Calendar.DAY_OF_MONTH)
return when {
years > 0 -> "$years years "
months > 0 -> "$months months"
else -> "$days days"
}
}
My Input of date is : Mon, 11 Sep 2023 15:49:32 GMT
i am getting this Exception : java.text.ParseException: Unparseable date: "Mon, 11 Sep 2023 15:49:32 GMT"
this is piece of code using this i am trying to calculate age its working fine till API level 33 in android but when i trying to run code using api level 34 i am getting parse exception in android can any one please help me how to fix this issue .
java.time
In March 2014, the modern Date-Time API supplanted the legacy date-time API. Since then, it has been strongly recommended to switch to
java.time, the modern date-time API.Your date-time string is compliant with
DateTimeFormatter.RFC_1123_DATE_TIMEformat. You can get the date part (LocalDate) out of theOffsetDateTime, obtained as a result of parsing the given date-time string using thisDateTimeFormatter.Get the current
LocalDateat UTC and then find the period between these two dates usingPeriod#between.where
formattedPeriod(Period)is a function returning aStringformatted in your desired manner.Output:
Online Demo
Learn about the modern date-time API from Trail: Date Time
Note: My area of expertise is Java and therefore I have written the code using Java language. Kotlin supports running Java code as it is. A Kotlin programmer can easily translate a Java code into the corresponding Kotlin code. Moreover, most part of my code can be reused as it is in the corresponding Kotlin program.
Update
Since your date-time string is in GMT/UTC, I have used
LocalDate.now(ZoneOffset.UTC)to get the currentLocalDatein GMT/UTC i.e. the key is to get theLocalDateusing the same time zone offset as your data-time string.As commented by Ole V.V., you can explicitly apply a time zone offset to the parsed date-time and the current
LocalDate. He has also provided a link to the solution in Kotlin using his approach. Here is the link to the code in Java using his approach.