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 ""
    }
}
相关推荐
liang_jy1 小时前
Android View Tag
android
liang_jy1 小时前
Android 架构中的统一分发与策略路由
android·架构
scan7243 小时前
长期记忆存储在数据库里
android
xingpanvip4 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
儿歌八万首6 小时前
Jetpack Compose 实战:实现一个动态平滑折线图
android·折线图·compose
李艺为10 小时前
Fake Device Test作假屏幕分辨率分析
android·java
zh_xuan10 小时前
github远程library仓库升级
android·github
峥嵘life11 小时前
Android蓝牙停用绝对音量原理
android
czlczl2002092512 小时前
IN和BETWEEN在索引效能的区别
android·adb
Volunteer Technology12 小时前
ES高级搜索功能
android·大数据·elasticsearch