Skip to content

Instantly share code, notes, and snippets.

@kimji1
Created March 3, 2020 15:02
Show Gist options
  • Select an option

  • Save kimji1/6557ba009095e12bce6b5439645ddafe to your computer and use it in GitHub Desktop.

Select an option

Save kimji1/6557ba009095e12bce6b5439645ddafe to your computer and use it in GitHub Desktop.
TimeZone, ZonedDateTime, Calendar, DateFormat
// java 8 이상에서 현재 시간에 맞는 각 타임존 별 시간 얻기
val pattern = DateTimeFormatter.ofPattern("HH:mm:ss")
val seoul = ZonedDateTime.now()
println(seoul.format(pattern))
val utc = seoul.withZoneSameInstant(ZoneOffset.UTC)
println(utc.format(pattern))
val vancouver = utc.withZoneSameInstant(ZoneId.of("America/Vancouver"))
println(vancouver.format(pattern))
println("==========================================================")
// 타임존 별 시간 얻어오기
val dateFormat = SimpleDateFormat("HH:mm:ss")
val calendar = Calendar.getInstance()
val seoulTimeZone = TimeZone.getDefault()
calendar.timeZone = seoulTimeZone
val seoulTime = dateFormat.format(calendar.time)
println(seoulTime)
val utcTimeZone = TimeZone.getTimeZone("UTC")
calendar.timeZone = utcTimeZone
dateFormat.timeZone = utcTimeZone
val utcTime = dateFormat.format(calendar.time)
println(utcTime)
val vancouverTimeZone = TimeZone.getTimeZone("America/Vancouver")
calendar.timeZone = vancouverTimeZone
dateFormat.timeZone = vancouverTimeZone
val vancouverTime = dateFormat.format(calendar.time)
println(vancouverTime)
println("==========================================================")
// calendar 이용해서 특정 시간 각 타임존에 맞는 시간 얻기
val time = "11:00:00"
val times = time.split(":")
calendar.set(Calendar.HOUR_OF_DAY, times[0].toInt())
calendar.set(Calendar.MINUTE, times[1].toInt())
calendar.set(Calendar.SECOND, times[2].toInt())
calendar.timeZone = seoulTimeZone
dateFormat.timeZone = utcTimeZone
// expect "02:00:00"
val timeToUTC = dateFormat.format(calendar.time)
println(timeToUTC)
// expect "18:00:00"
calendar.timeZone = utcTimeZone
dateFormat.timeZone = vancouverTimeZone
val timeToVancouver = dateFormat.format(calendar.time)
println(timeToVancouver)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment