DevJaewoo
DevJaewoo

Reputation: 3

Get absolute time using result of System.currentTimeMillis in android

I defined BuildConfig field to use as app version.

buildConfigField "long", "BUILDTIME", System.currentTimeMillis() + "L"

And I can get that value properly in my MainActivity.

binding.buttonTest.text = "Build Version is: " + SimpleDateFormat("yyyyMMddHHmmss", Locale.KOREA)
                               .format(BuildConfig.BUILDTIME)

But when testing my app on test phone and AVD which has different time zone,
the string that SimpleDateFormat returns are not same.

-- RESULT --
Test phone: Build Version is: 20220502172527
AVD: Build Version is: 20220502082738

I think it's because SimpleDateFormat gives relative time, not absolute time.
How can I get absolute time in android with result of System.currentTimeMillis()?
Thanks.

Note: I don't want to use Date(), because all of it's get methods are deprecated.

Upvotes: 0

Views: 593

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 339342

tl;dr

You seem to not care about fractional second, so use a count of whole seconds since the epoch reference of 1970-01-01T00:00Z.

Instant
.now()
.getEpochSecond()

Generate text.

Instant
.ofEpochSecond(
    mySavedCountOfSecondsFromEpoch
)  // Returns an `Instant`.
.atOffset( 
    ZoneOffset.UTC 
) // Returns an `OffsetDateTime`.
.format(
    DateTimeFormatter
    .ofPattern( "uuuuMMddHHmmss" )
)  // Returns a `String`. 

20220501123456

Avoid legacy classes

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes.

Android 26+ includes an implementation. For earlier Android, the latest tooling brings most of the functionality via “API desugaring”.

Instant

The call to System.currentTimeMillis() can be replaced with Instant.now().toEpochMilli().

Parse the count of milliseconds since the epoch reference of first moment of 1970 as seen in UTC.

Instant instant = Instant.ofEpochMilli( myMillis ) ;

OffsetDateTime

For more flexible generating of text, convert from the basic building-block Instant class to OffsetDateTime.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;

DateTimeFormatter

Define a formatting pattern.

Be aware that your desired format involves data loss, by lopping off the fractional second.

No need for the locale you passed. In your desired format nothing needs localization.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) ;

Generate text.

String output = odt.format( f ) ;

Upvotes: 3

bjojo
bjojo

Reputation: 19

You need to specify the TimeZone your SimpleDateFormat object uses with setTimeZone(TimeZone.UTC).

Upvotes: 1

Related Questions