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 ""
    }
}
相关推荐
大模型玩家七七18 分钟前
效果评估:如何判断一个祝福 AI 是否“走心”
android·java·开发语言·网络·人工智能·batch
Aurora41928 分钟前
Android事件分发逻辑--针对事件分发相关函数的讲解
android
似霰1 小时前
Android 日志系统4——logd 写日志过程分析一
android
youyoulg2 小时前
利用Android Studio编译Android上可直接执行的二进制
android·ide·android studio
闽农2 小时前
Android ANR 调用栈溯源
android·anr
似霰2 小时前
Android 日志系统7——Android 平台日志丢失问题分析
android·log
·云扬·2 小时前
MySQL Undo Log 深度解析:事务回滚与 MVCC 的底层支柱
android·数据库·mysql
fareast_mzh2 小时前
如何检测、排除手机控制屏幕
android
左手厨刀右手茼蒿2 小时前
Flutter for OpenHarmony 实战:DartX — 极致简练的开发超能力集
android·flutter·ui·华为·harmonyos