我有一個問題,我得到一個String假定為 UTC 的 DateTime -
2022-07-03T11:42:01
我的任務是將其轉換為這樣的 UTC 格式字串 -
yyyy-MM-dd'T'HH:mm:ss'Z'
所以它應該看起來像這樣 -
2020-07-03T11:42:01.000Z
到目前為止,這是我的嘗試-
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.Locale
import java.util.TimeZone
fun main() {
val myDateTimeString = "2022-04-24T20:39:47"
val ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
val utc = TimeZone.getTimeZone("UTC");
var isoFormatter = SimpleDateFormat(ISO_FORMAT);
isoFormatter.setTimeZone(utc);
println(isoFormatter.format(myDateTimeString).toString())
}
我玩過一些變體,但出現以下例外 -
> Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format (:-1)
at java.text.Format.format (:-1)
at FileKt.main (File.kt:22)
有人可以幫忙嗎?
謝謝 :)
鏈接到我在 Kotlin Playground 中的示例 -我的示例
uj5u.com熱心網友回復:
你有java.time,這意味著你只需幾行代碼就可以得到想要的結果。
應該執行以下步驟:
- 將輸入決議
String為 aLocalDateTime,這特別適合此步驟,因為它僅存盤日期和時間,明確沒有偏移量或區域 - 附加所需的
ZoneOffset,這里只是ZoneOffset.UTC - 為您想要的輸出格式定義一個
DateTimeFormatter(或使用內置的,全部嘗試) - 列印(或回傳)結果,然后是型別
OffsetDateTime
例子:
fun main() {
val input = "2022-07-03T11:42:01"
// parse it to a LocalDateTime (date & time without zone or offset)
val offsetDateTime: OffsetDateTime = LocalDateTime.parse(input)
// and append the desired offset
.atOffset(ZoneOffset.UTC)
// define a formatter for your desired output
val formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSX",
Locale.ENGLISH)
// and use it in order to print the desired result
println("$input --> ${offsetDateTime.format(formatter)}")
}
示例的輸出:
2022-07-03T11:42:01 --> 2022-07-03T11:42:01.000Z
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/516257.html
