Last active
November 23, 2021 15:16
-
-
Save jibbo/72c5bd09ed6223038f97f989f5378583 to your computer and use it in GitHub Desktop.
Convert date in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test | |
fun `convert Timezone`() { | |
val serverTimeInUTC = "2021-11-19 09:50:36" // Friday 19 Nov 2021 at 9:50 | |
val utcFormatter = SimpleDateFormat(DateUtils.TIMESTAMP_FORMAT) | |
utcFormatter.timeZone = TimeZone.getTimeZone("UTC") | |
val utcDate = utcFormatter.parse(serverTimeInUTC) | |
val utcDateString = utcFormatter.format(utcDate) | |
val otherFormatter = SimpleDateFormat(DateUtils.TIMESTAMP_FORMAT) | |
otherFormatter.timeZone = TimeZone.getTimeZone("Europe/Bucharest") | |
val otherDateString = otherFormatter.format(utcDate) | |
println("serverTime: $utcDateString, converted time: $otherDateString") | |
assertNotEquals(utcDateString, otherDateString) | |
} | |
@Test | |
fun `convert timestamp`() { | |
val serverTimestamp = 1637678180000L // 23 November 2021 14:36 UTC | |
val utcTimeZone = TimeZone.getTimeZone("UTC") | |
val serverCalendar = Calendar.getInstance(utcTimeZone) | |
serverCalendar.timeInMillis = serverTimestamp | |
val localTimezone = TimeZone.getTimeZone("Europe/Rome") | |
val localCalendar = Calendar.getInstance(localTimezone) | |
localCalendar.timeInMillis = serverTimestamp | |
// this is just to compare the times in an easy way | |
val formatter = SimpleDateFormat(DateUtils.TIMESTAMP_FORMAT) | |
formatter.timeZone = utcTimeZone | |
val serverTimeInUTC = formatter.format(serverCalendar.time) | |
formatter.timeZone = localTimezone | |
val localTime = formatter.format(localCalendar.time) | |
println("serverTime: $serverTimeInUTC, converted time: $localTime") | |
assertNotEquals(serverTimeInUTC, localTime) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment