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 ""
    }
}
相关推荐
Xzaveir9 小时前
不要用一个状态表示“号码已认证”:企业号码身份的四域模型
android·人工智能
(Charon)9 小时前
【C++】手写 MySQL 连接池(二):同步连接的获取、加锁与释放
android
zhangjin112010 小时前
AOSP下载
android
Mico1811 小时前
MySQL 8.0.35 GTID 主从复制搭建-基于GITD
android·mysql·adb
YXL1111YXL13 小时前
LeakCanary 源码解析检测泄露工作机制(一)
android·leakcanary
且随疾风前行.15 小时前
Android Binder 驱动 - 内核驱动层源码初探
android·网络·binder
额恩6615 小时前
AI 智能体从零搭建实战教程——扣子
android·rxjava·coze
hunterandroid15 小时前
前台服务适配与线上排查:通知权限、启动限制和任务保活
android·前端
帅次15 小时前
Android 高级工程师面试:Flutter 渲染与性能 近1年高频追问 20 题
android·flutter·面试·渲染·性能
糖果店的幽灵16 小时前
【langgraph 从入门到精通graphApi 篇】Command 与动态流程控制
android·java·数据库·人工智能·langgraph