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 ""
    }
}
相关推荐
黄林晴27 分钟前
官方实战指南!Compose 项目无缝迁移 KMP
android·kotlin
tryqaaa_37 分钟前
学习日志(五)【php反序列化全加例题】【pop链,字符逃逸,session,伪协议】
android·学习·php·web·pop·session
jingling55541 分钟前
自建技术博客实战(三):工具专栏——地图定位、声音复刻与 rembg 抠图
android·开发语言·前端·ai·nextjs
Co_Hui1 小时前
Android:Service 启动
android
爱睡觉1111 小时前
Android 底层输入系统改造实录:把 gpio-keys "凭空捏造"成虚拟键盘
android
plainGeekDev1 小时前
XML Shape/Selector → Kotlin 动态创建
android·java·kotlin
plainGeekDev1 小时前
Java 自定义 View → Kotlin 自定义 View
android·java·kotlin
码云骑士2 小时前
Android ART运作流程
android
万能小林子2 小时前
如何将网页在线转APP?5种打包工具对比速成指南(含在线/手机/电脑方案)
android·ios·uni-app·web app·wap2app·app打包·app封装
梅塔鲁2 小时前
Kotlin成安卓开发首选
android