JodaTime: How to get a String representation in the format "HH:mm Z" from a LocalTime

Chriss :

Assume we have a Joda LocalTime and want to display its hour and minute and timezone, how to do it?

Actually this doesn't work:

 val chronology= ISOChronology.getInstance(DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/St_Vincent")))
 val localTime = LocalTime(12, 45, 0, 0, chronology)
 val string = localTime.toString("HH:mm Z") // returns "12:45 ", expected "12:45 -4"
madhead :

Local times does not have an attached timezone by definition. But a Chronology is not a timezone, it's a way people measure time (like Chinese years, or Buddhist). You could omit it in your code and the result would be the same as ISOChronology (the way we measure time in "Western Culture") is the default.

You need to turn it into a zoned date time:

fun main(args: Array<String>) {
    val localTime = LocalTime(12, 45, 0, 0)
    val string = localTime
            .toDateTimeToday(
                    DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/St_Vincent"))
            )
            .toString("HH:mm Z")

    println(string)
}

The result is: 12:45 -0400

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310532&siteId=1