(Using Java syntax, as I’ve not yet learned Kotlin.)
tl;dr
Instant // Represents a moment as seen in UTC, that is, with an offset from UTC of zero hours-minutes-seconds.
.ofEpochMilli(
System.currentTimeMillis() // Returns a `long` value, a count of milliseconds since the epoch reference of 1970-01-01T00:00Z.
) // Returns an `Instant` object.
.atZone(
ZoneId.systemDefault()
) // Returns a `ZonedDateTime` object.
.toLocalDate() // Returns a `LocalDate` object.
.format(
DateTimeFormatter
.ofPattern( "dd-MM-uuuu" ) // Returns a `DateTimeFormatter` object.
) // Returns a `String` object.
java.time
timestamp = System.currentTimeMillis()
The method System.currentTimeMillis()
returns a count of milliseconds since the epoch reference of the first moment in 1970 in UTC, 1970-01-01T00:00Z.
You can parse that number into an Instant
, which represents a moment as seen in UTC as well (an offset from UTC of zero hours-minutes-seconds).
Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;
To get that same number:
long millisSinceEpoch = Instant.now().toEpochMilli() ;
Ever better, just stop using System.currentTimeMillis()
. Just use Instant
in the first place. The Instant
class resolves to nanoseconds, though most implementations are constrained to capturing the current moment in microseconds because of the limits of today's computer hardware clocks. Still, that is better that mere milliseconds.
Instant instant = Instant.now() ; // Likely contains microseconds in Java 9+, though limited to milliseconds in Java 8 (generally).
Your code:
var date = Date(timestamp)
No, no, no. Never use the terrible legacy class java.util.Date
nor java.sql.Date
. Both were supplanted years ago by the modern java.time classes built into Java 8+, defined by JSR 310. Those two classes were specifically replaced by java.time.Instant
and java.time.LocalDate
, respectively.
Android 26+ has java.time classes built-in. For earlier Android, the latest tooling provides access to most of the java.time functionality via “API desugaring”.
You said:
convert the same to normal format ex: 15-03-2020 (dd-mm-yyyy)
Determining the date requires a time zone. For any given moment, the date around the world varies by time zone (think about it!).
Apply a time zone (ZoneId
) to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ; // Or perhaps `ZoneId.systemDefault()`.
ZonedDateTime zdt = instant.atZone( z ) ;
Extract the date-only.
LocalDate ld = zdt.toLocalDate() ;
Date-time objects do not have text, so they do not have “format”. You need to generate text in your desired format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = ld.format( f ) ;