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 ""
    }
}
相关推荐
call me by ur name23 分钟前
ERNIE 5.0 Technical Report论文解读
android·开发语言·人工智能·机器学习·ai·kotlin
kerli37 分钟前
Compose 组件:Box 核心参数及其 Bias 算法
android·前端
BLUcoding1 小时前
Android 常用控件及核心属性
android
遥不可及zzz1 小时前
[特殊字符] Android AAB 一键安装工具配置指南
android·macos
私人珍藏库1 小时前
【Android】一键硬核锁手机
android·智能手机·app·工具·软件
TTTao23332 小时前
自用Android项目框架备份
android
沃尔威武2 小时前
性能调优实战:从火焰图定位到SQL优化的全流程
android·数据库·sql
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.3 小时前
基于MySQL一主一从环境添加多个新从库
android·mysql·adb
JJay.4 小时前
Android App Functions 深入理解
android
开发_李行4 小时前
简历对应知识点总结--专业技能5
android