It may sound very funny and basic, but I am struggling with creating a DateTime kind of object in Kotlin by passing the number of seconds from epoch to it.
Either the examples that I am getting are of the libraries that require API level 26, or just talk about format conversion from string of DD-MM-YYYY to some other.
I have tried "LocalDateTime", "Timestamp", "Date" so far, but Kotlin either refuses to recognise them or the doesn't agree to the function parameters, or is unable to resolve namespace conflict. Or the examples are of Java, which don't work in Kotlin or don't have equivalent in Kotlin.
With Date() I am getting error "Cannot access '': It is private in Date()"
With LocalDate, LocalDateTime, I am getting the API level error
With Timestamp I am getting error "None of the following functions can be called with the arguments supplied". I am passing Long as the parameter as mentioned in documentation. But it is expecting "Parcel" or "Date".
Could someone please help?
Update: In recent versions of Android tooling, API desugaring brings to older versions of Android much of the java.time functionality that is built into Android 26 and later.
Date
, Calendar
, or SimpleDateFormat
.The legacy classes such as Date
& Calendar
are terrible, created by people who did not understand date-time handling. These classes were supplanted years ago by the modern java.time classes defined in JSR 310.
The Instant
class replaces the Date
class, both representing a moment in UTC (an offset of zero hours-minutes-seconds).
Instant instant = Instant.now() ; // Capture the current moment in UTC.
The Calendar
class, or more precisely, its most commonly-used concrete subclass GregorianCalendar
is replaced by ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
Best to avoid the legacy date-time classes entirely. But sometimes you may need to interoperate with old code not yet updated to java.time. In that case, convert. Look to new to…
/from…
conversion methods added to the old classes.
Calendar calendar = GregorianCalendar.from( zdt ) ;
…and…
ZonedDateTime zdt = ( ( GregorianCalendar ) calendar ).toZonedDateTime() ;
The java.time classes are built into Java 8 and later, and Android 26 and later.
For Java 6 & 7, use the back-port found in the ThreeTen-Backport project. Most of the java.time functionality is found there. This project is led by the same man leading the java.time project and JSR 310, Stephen Colebourne.
For Android before 26, use the adaptation of that back-port to Android, the ThreeTenABP project.
I use Calendar for Kotlin
val date = Calendar.getInstance()
date.timeInMillis = 5000000
txtDate.text = date.time.toString()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With