一、效果图
图1,中国的时间格式
图2,美国的时间格式
二、StringUtil.kt代码
bash
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
object StringUtil {
fun formatTimestamp(currentTime: Long): String {
var sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
return sdf.format(Date(currentTime))
}
fun formatDateTimeLocale(
timeMillis: Long?,
dateStyle: Int = DateFormat.SHORT,
timeStyle: Int = DateFormat.SHORT
): String {
if (timeMillis == null || timeMillis <= 0L) {
return ""
}
try {
val locale = Locale.getDefault()
val dateFormat = DateFormat.getDateInstance(dateStyle, locale)
val timeFormat = DateFormat.getTimeInstance(timeStyle, locale)
val calendar: Calendar = Calendar.getInstance(locale)
calendar.time = Date(timeMillis)
val formattedDate = dateFormat.format(calendar.time)
var formattedTime = timeFormat.format(calendar.time)
return "$formattedDate $formattedTime"
} catch (e: Exception) {
}
return ""
}
}