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 ""
    }
}
相关推荐
YB13759 小时前
jetpack compose 副作用 SideEffect
android·kotlin
CHB10 小时前
uni-app x 蒸汽模式 性能测试基准报告 Benchmark【Android版】
android·ios·uni-app
带娃的IT创业者11 小时前
拆掉那堵墙:LibrePods 如何让 AirPods 在 Android 上重获新生
android·开源项目·airpods·librepods·生态解锁
_阿南_13 小时前
flutter 展示的字体突然奔放了
android·flutter·ios
文人sec16 小时前
MySQL事务与索引做了什么?
android·笔记·mysql
刘洋浪子17 小时前
AndroidStudio保存日志菜单
android
朱涛的自习室17 小时前
从 Prompt 到 Graph:AI 工程的进化史
android·前端·人工智能
2501_9327502617 小时前
Android 中 Serializable 与 Parcelable 的对比与选择
android
FungLeo18 小时前
Flutter 两个反直觉布局坑:ListTile 水波纹 / VerticalDivider 踩坑实录
android·flutter
1570925113419 小时前
ViewBinding与DataBinding区别与选型
android