12

I know this question may be duplicated but I didn't find any answer for my problem, I'm using LocalDateTime in my Android app that requires API 26 and my device's API is 25.

What can I do? Your help will be very appreciated.

ישו אוהב אותך
  • 22,515
  • 9
  • 59
  • 80
Anna
  • 133
  • 1
  • 4
  • It is quite obvious that you can't use newer features on older devices. You have to either implement this feature by yourself, or find a library that provides similar functionality – Vladyslav Matviienko Jun 21 '19 at 06:25

3 Answers3

21

You need to use https://github.com/JakeWharton/ThreeTenABP to be able using LocalDateTime with Android API < 26.

Add the dependencies to your project (please follow the project README):

implementation 'com.jakewharton.threetenabp:threetenabp:1.2.1'

Then change your LocalDateTime import from:

import java.time.LocalDateTime;

to:

import org.threeten.bp.LocalDateTime;

Update:

The library mentioned above is no longer the best way as mentioned in JakeWharton/ThreeTenABP README:

Attention: Development on this library is winding down. Please consider switching to Android Gradle plugin 4.0, java.time.*, and its core library desugaring feature in the coming months.

To use LocalDateTime in older API levels, use the desugaring feature from Gradle plugin 4.0: https://developer.android.com/studio/write/java8-support#library-desugaring

fsljfke
  • 359
  • 4
  • 13
ישו אוהב אותך
  • 22,515
  • 9
  • 59
  • 80
10

The best way to use LocalDateTime on a lower versions of Android is by desugaring (you must have Android Gradle plugin version 4.0 or higher). Just add the below lines to your app module gradle file:

enter image description here

Finally, add the ff. dependency to your dependencies block:

coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.10'

Jim
  • 397
  • 5
  • 17
3

You can use ThreeTenBP. But for android it is recommended to use Jake Wharton's ThreeTenABP.

Why not use ThreeTenBP?

Similar to the problems with using Joda-Time on Android, the threetenbp uses a JAR resource for loading timezone information. This is an extremely inefficient mechanism on Android.

This library places the timezone information as a standard Android asset and provides a custom loader for parsing it efficiently.

Why not use Joda-Time?

Joda-Time has a very large API which brings with it a very large binary size and large method count. The creator of both JSR-310 and Joda-Time has also said that while Joda-Time isn't broken, it does have design flaws.

If you are using Joda-Time already, there's little reason to switch unless its size or method count is relevant to you. For new projects, however, this library offers the standard APIs in Java 8 as a much smaller package in not only binary size and method count, but also in API size.

These explanations came from Jake Wharton's ThreeTenABP.

Community
  • 1
  • 1
Tenten Ponce
  • 2,256
  • 1
  • 9
  • 27