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 ""
    }
}
相关推荐
好的佩奇1 小时前
Dart 之可迭代对象与生成器
android·flutter·dart
_祝你今天愉快1 小时前
Paint Cavans高级绘制:[三] Canvas高阶使用技巧-变换,状态保存,离屏缓冲,粒子特效
android
小乖写代码2 小时前
提交注册验证 · WhatsApp /v2/register
android·网络·账号注册
二流小码农6 小时前
鸿蒙开发:router组件升级,彻底告别手动配置
android·ios·harmonyos
Digitally7 小时前
如何在安卓设备上使用 4 种简单方法将应用移动到 SD 卡
android
booboosui8 小时前
录一遍就会:8 种步骤、6 类失败,卡住时只修那一步
android
阿杰m8 小时前
Android源码第十五章:Camera2 与 CameraService——一帧图像怎样回到应用
android
恋猫de小郭14 小时前
Flutter Analyzer 系列坑推进,必看,AI 时代这玩意最吃你内存
android·前端·flutter
LinXunFeng1 天前
拿竞品 App 一扫,技术栈全暴露了
android·flutter·开源
Gracker1 天前
AIW:从系统机制到性能排查,一本可以对照源码的 Android 电子书
android