如果您的输入是时间戳(Long)而不是UTC时间,由于这是在Android上,您可以执行以下操作:
fun DateFormat.formatUtcEpochSecond(epochSecond: Long): String = format(CalendarEx.getFromEpochSecond(epochSecond).time)
fun DateFormat.formatUtcEpochMs(epochMilli: Long): String = format(CalendarEx.getFromEpochMilli(epochMilli).time)
CalendarEx.kt
object CalendarEx {
@JvmStatic
fun getFromEpochMilli(epochMilli: Long): Calendar {
val cal = Calendar.getInstance()
cal.timeInMillis = epochMilli
return cal
}
@JvmStatic
fun getFromEpochSecond(epochSecond: Long): Calendar {
val cal = Calendar.getInstance()
cal.timeInMillis = epochSecond * 1000L
return cal
}
}
DateHelper.kt
@JvmStatic
fun getFormatDateUsingDeviceSettings(context: Context): java.text.DateFormat {
return DateFormat.getDateFormat(context) ?: SimpleDateFormat("yyyy/MM/dd", Locale.getDefault())
}
@JvmStatic
fun getFormatTimeUsingDeviceSettings(context: Context): java.text.DateFormat {
return DateFormat.getTimeFormat(context) ?: SimpleDateFormat("HH:mm", Locale.getDefault())
}
使用示例:
val dateFormat = DateHelper.getFormatDateUsingDeviceSettings(this)
val timeFormat = DateHelper.getFormatTimeUsingDeviceSettings(this)
val timeStampSecondsInUtc = 1516797000L
val localDateTime = Instant.ofEpochSecond(timeStampSecondsInUtc).atZone(ZoneId.ofOffset("UTC", ZoneOffset.ofHours(0))).toLocalDateTime()
Log.d("AppLog", "input time in UTC:" + localDateTime)
Log.d("AppLog", "formatted date and time in current config:${dateFormat.formatUtcEpochSecond(timeStampSecondsInUtc)} ${timeFormat.formatUtcEpochSecond(timeStampSecondsInUtc)}")
Locale
主要用于生成两种形式的日期时间字符串表示:(a) 确定用于本地化月份名称等的人类语言,以及 (b) 确定用于决定缩写、大写、标点符号等方面的文化习惯。而时区是完全独立的问题。例如,你可能有一个在印度的加拿大用户,因此你需要使用Locale.CANADA_FRENCH
和印度时区ZoneId.of("Asia/Kolkata")
。 - Basil Bourque