日期转换 24 小时和 12 小时 - Kotlin
Date Conversion 24 hours and 12 hours - Kotlin
我从服务器获取的 UTC 格式的日期低于日期:
2021-05-20 09:14:55
现在,我必须将它转换成本地的 24 小时格式和 12 小时格式。
要将其转换为 24 小时格式,我已按如下方式完成:
val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
df.timeZone = TimeZone.getTimeZone("UTC")
val date = df.parse(dataDate)
df.timeZone = TimeZone.getDefault()
val formattedDate = df.format(date)
得到的结果为:2021-05-20 14:44:55(当地时间 24 小时)
现在,我尝试将相同的日期转换为本地 12 小时格式,如下所示:
val utc = TimeZone.getTimeZone("UTC")
val inputFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.ENGLISH)
inputFormat.timeZone = utc
val outputFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa",
Locale.ENGLISH)
outputFormat.timeZone = utc
val dateInput = inputFormat.parse(dataDate)
val output = outputFormat.format(dateInput)
它给我的输出是 2021-05-20 09:14:55 AM(当地时间 12 小时)
我认为只是添加 AM 作为后缀是错误的。这可能是错误的,因为如果 24 小时日期结果是 2021-05-20 14:44:55 那么 12 小时日期结果应该是 2021-05-20 02:44:55下午
可能是什么问题?
您正在使用 TimeZone.getDefault()
打印 24 小时制,TimeZone.getTimeZone("UTC")
打印 12 小时制。
df.timeZone = TimeZone.getDefault()
val formattedDate = df.format(date)
outputFormat.timeZone = utc
val output = outputFormat.format(dateInput)
TimeZone.getDefault()
使用您当地的时区,在本例中不是 UTC。
12 小时制与 24 小时制一样使用本地时区。
outputFormat.timeZone = TimeZone.getDefault()
我从服务器获取的 UTC 格式的日期低于日期:
2021-05-20 09:14:55
现在,我必须将它转换成本地的 24 小时格式和 12 小时格式。
要将其转换为 24 小时格式,我已按如下方式完成:
val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
df.timeZone = TimeZone.getTimeZone("UTC")
val date = df.parse(dataDate)
df.timeZone = TimeZone.getDefault()
val formattedDate = df.format(date)
得到的结果为:2021-05-20 14:44:55(当地时间 24 小时)
现在,我尝试将相同的日期转换为本地 12 小时格式,如下所示:
val utc = TimeZone.getTimeZone("UTC")
val inputFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.ENGLISH)
inputFormat.timeZone = utc
val outputFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa",
Locale.ENGLISH)
outputFormat.timeZone = utc
val dateInput = inputFormat.parse(dataDate)
val output = outputFormat.format(dateInput)
它给我的输出是 2021-05-20 09:14:55 AM(当地时间 12 小时)
我认为只是添加 AM 作为后缀是错误的。这可能是错误的,因为如果 24 小时日期结果是 2021-05-20 14:44:55 那么 12 小时日期结果应该是 2021-05-20 02:44:55下午
可能是什么问题?
您正在使用 TimeZone.getDefault()
打印 24 小时制,TimeZone.getTimeZone("UTC")
打印 12 小时制。
df.timeZone = TimeZone.getDefault()
val formattedDate = df.format(date)
outputFormat.timeZone = utc
val output = outputFormat.format(dateInput)
TimeZone.getDefault()
使用您当地的时区,在本例中不是 UTC。
12 小时制与 24 小时制一样使用本地时区。
outputFormat.timeZone = TimeZone.getDefault()