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 小时前
m3颜色定义
android·compose
麻辣璐璐2 小时前
EditText属性运用之适配RTL语言和LTR语言的输入习惯
android·xml·java·开发语言·安卓
北京自在科技2 小时前
谷歌 Find Hub 网页端全面升级:电脑可直接管理追踪器与耳机
android·ios·安卓·findmy
Rush-Rabbit3 小时前
魅族21Pro刷ColorOS16.0操作步骤
android
爪洼传承人3 小时前
AI工具MCP的配置,慢sql优化
android·数据库·sql
学习使我健康3 小时前
MVP模式
android·github·软件工程
xiangxiongfly9153 小时前
Android MMKV
android·mmkv
北漂Zachary5 小时前
PHP3.0:改变Web开发的里程碑
android·php·laravel
fundroid5 小时前
Google 发布 Android Skill & Android CLI:大幅提升 Android Agent 能力
android·agent·cli·skill
seabirdssss5 小时前
Flutter 开发环境配置
android·windows·flutter·adb