Skip to content

Instantly share code, notes, and snippets.

@AdamMc331
Created September 25, 2020 15:59
Show Gist options
  • Save AdamMc331/a7056c31c25474604485d48fb97ef72f to your computer and use it in GitHub Desktop.
Save AdamMc331/a7056c31c25474604485d48fb97ef72f to your computer and use it in GitHub Desktop.
Gives an example of how I take a date that is GMT and convert it to the TimeZone that I want.
/**
* Given a supplied [dateString] that matches our [RFC_3339_FORMAT], convert it to a
* [Calendar] instance for the corresponding [timeZoneString].
*
* The only way I've been able to do this is:
* 1. Take the date string, which is GMT, and convert it to a Date.
* 2. Update the TZ on our SimpleDateFormat, to get the string in the desired TimeZone.
* 3. Reverse engineer that back into a date.
* 4. Return this calendar.
*
* The step to a string seems intermediary. Why can't I create a calendar at GMT timezone, and then
* tell it to convert?
*/
fun getCalendarWithTimeZone(
dateString: String,
timeZoneString: String
): Calendar {
val dateFormatter = SimpleDateFormat(RFC_3339_FORMAT, Locale.getDefault())
dateFormatter.timeZone = TimeZone.getTimeZone("GMT")
val dateInGmt = dateFormatter.parse(dateString)
val timeZone = TimeZone.getTimeZone(timeZoneString)
dateFormatter.timeZone = timeZone
val updatedDateString = dateFormatter.format(dateInGmt)
val updatedDate = dateFormatter.parse(updatedDateString)
val calendar = Calendar.getInstance(timeZone)
calendar.time = updatedDate
return calendar
}
class DateTesting {
@Test
fun convertTimeToNY() {
val dateString = "2020-09-24T22:00:00Z"
val timeZoneId = "America/New_York"
val calendar = getCalendarWithTimeZone(dateString, timeZoneId)
assertThat(calendar.get(Calendar.HOUR)).isEqualTo(6)
}
}
@AdamMc331
Copy link
Author

Here is the same code using the java.time package. Note that I compared hour to 18 instead of 6, because I'm not sure how to get PM but that can be resolved later.

At least this is a cleaner way of converting dates:

fun java8Date(
    dateString: String,
    timeZoneString: String
): LocalDateTime {
    val gmtZone = ZoneId.of("GMT")
    val userZone = ZoneId.of(timeZoneString)

    val dateTimeFormatter = DateTimeFormatter.ofPattern(RFC_3339_FORMAT)
    val localDateInGMT = LocalDateTime.parse(dateString, dateTimeFormatter)
    val zonedDateGMT = ZonedDateTime.of(localDateInGMT, gmtZone)

    val userZonedDate = zonedDateGMT.withZoneSameInstant(userZone)

    return userZonedDate.toLocalDateTime()
}


class DateTesting {
    @Test
    fun convertTimeToNY() {
        val dateString = "2020-09-24T22:00:00Z"
        val timeZoneId = "America/New_York"

        val localDate = java8Date(dateString, timeZoneId)
        assertThat(localDate.hour).isEqualTo(18)
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment