Fabio Lanza
Fabio Lanza

Reputation: 175

Android java.time.LocalDateTime

I am coding an Android application, which should receive a java.time.LocalDateTime object through an HTTP REST API that I developed in the server side.

The problem is that Android is still in Java 7, and java.time is only available in Java 8.

Having that said, what is the best way to represent a variable that contains date and time in Android? I prefer not to use sql.timestamp.

Thank you!

Upvotes: 4

Views: 11906

Answers (5)

Cristan
Cristan

Reputation: 14095

You can use LocalDateTime if your minSdkVersion is 26 (Android 8.0) or higher 1. Otherwise, you can use core library desugaring.

android {
    defaultConfig {
        // Required when setting minSdkVersion to 20 or lower
        multiDexEnabled true
    }

    compileOptions {
        // Flag to enable support for the new language APIs
        coreLibraryDesugaringEnabled true
        // Sets Java compatibility to Java 8
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}

Upvotes: 3

Marvin
Marvin

Reputation: 14355

Back-port

You could use the ThreeTen Android Backport which is an Android adaption to the original ThreeTen-Backport that backports much of the new java.time api back to Java SE 6 and SE 7.

See this answer to get started.

Upvotes: 5

holi-java
holi-java

Reputation: 30686

a LocalDateTime object has been serialized to a string|long JSON property through an HTTP REST API.

so you just to do is adaptee the JSON property to a Date object, and format a Date object to the JSON property if you want to send a Date object to the server which only accept a LocalDateTime object.

almost all the JSON library providing a dateFormat for serializing/deserializing a string to a Date, and convert long timestamp to Date is so simple:

Date date = new Date(timestamp);

Upvotes: 0

davidxxx
davidxxx

Reputation: 131396

Why bother you using Date or Calendar previous to Java 8 while the Android version of Joda-time (that is very close from the Java 8 dates) is available ?

Here is the GIT repo/website for more information :

https://github.com/dlew/joda-time-android

Upvotes: 3

Jie Heng
Jie Heng

Reputation: 216

Use the java.util.Calendar which is available in Java 7. Refer to the link below for more information: https://developer.android.com/reference/java/util/Calendar.html

Calendar rightNow = Calendar.getInstance(); //initialized with the current date and time

Upvotes: 1

Related Questions