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 ""
    }
}
相关推荐
雨白15 小时前
Jetpack Compose Navigation 2.x 详解
android·android jetpack
Android系统攻城狮18 小时前
Android内核进阶之获取DMA地址snd_pcm_sgbuf_get_addr:用法实例(九十一)
android·pcm·android内核·音频进阶·pcm硬件参数
清空mega18 小时前
Android Studio移动应用基础教程(前言)
android·ide·android studio
2501_9371454118 小时前
2025IPTV 源码优化版实测:双架构兼容 + 可视化运维
android·源码·源代码管理·机顶盒
zhoutanooi20 小时前
安卓bp文件编译学习
android·学习
aramae21 小时前
MySQL数据库入门指南
android·数据库·经验分享·笔记·mysql
百锦再21 小时前
选择Rust的理由:从内存管理到抛弃抽象
android·java·开发语言·后端·python·rust·go
whatever who cares1 天前
在Java/Android中,List的属性和方法
android·java
油炸小波1 天前
09-微服务原理篇(XXLJOB-幂等-MySQL)
android·mysql·微服务
果子没有六分钟1 天前
setprop debug.hwui.profile visual_bars有什么作用
android