Created
September 25, 2020 15:59
-
-
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.
This file contains hidden or 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
/** | |
* 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is the same code using the java.time package. Note that I compared hour to
18
instead of6
, 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: