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 ""
    }
}
相关推荐
珊瑚里的鱼1 小时前
C++的强制类型转换
android·开发语言·c++
问心无愧05131 小时前
ctf show web入门102
android·java·前端·笔记
Kapaseker2 小时前
Kotlin 相等的奥义
android·kotlin
Lyyaoo.2 小时前
【MySQL】锁机制
android·数据库·mysql
DS随心转插件2 小时前
DeepSeek 代码手机端导出与 AI 辅助方案实测
android·人工智能·chatgpt·智能手机·deepseek·ai导出鸭
JohnnyDeng942 小时前
【Android】Flow vs LiveData:选型指南与迁移实践
android·kotlin·livedata·flow
plainGeekDev2 小时前
线程安全集合 → 协程安全替代
android·java·kotlin
zhangphil3 小时前
Kotlin管道Channel构造函数参数capacity值RENDEZVOUS与UNLIMITED
android·kotlin
plainGeekDev3 小时前
Timer → Coroutines
android·java·kotlin
Coffeeee3 小时前
Android17应用内存限制--App:我人不舒服,系统:那你走吧
android·google·kotlin