Android:将时间戳转换为本地时间格式

一、效果图

图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 ""
    }
}
相关推荐
田梓燊10 分钟前
leetcode 142
android·java·leetcode
angerdream31 分钟前
Android手把手编写儿童手机远程监控App之JAVA基础
android
菠萝地亚狂想曲1 小时前
Zephyr_01, environment
android·java·javascript
sTone873751 小时前
跨端框架通信机制全解析:从 URL Schema 到 JSI 到 Platform Channel
android·前端
sTone873751 小时前
Java 注解完全指南:从 "这是什么" 到 "自己写一个"
android·前端
catoop1 小时前
Kotlin 协程在 Android 开发中的应用:定义、优势与对比
android·kotlin
撒旦物种1 小时前
Android WebView 获取内容高度
android·webview
空中海2 小时前
第七章:安卓性能优化
android·性能优化
空中海2 小时前
第四章:导航与路由
android
2501_916007474 小时前
iOS逆向工程:详细解析ptrace反调试机制的破解方法与实战步骤
android·macos·ios·小程序·uni-app·cocoa·iphone