Skip to content

Instantly share code, notes, and snippets.

@jibbo
Last active November 23, 2021 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jibbo/72c5bd09ed6223038f97f989f5378583 to your computer and use it in GitHub Desktop.
Save jibbo/72c5bd09ed6223038f97f989f5378583 to your computer and use it in GitHub Desktop.
Convert date in Kotlin
@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