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 ""
    }
}
相关推荐
奔跑吧 android几秒前
【车载audio】【CarAudioService 05】【车载 Android 系统调试深度指南:解析 dumpsys car_service】
android·audio·audioflinger·aosp15·车载音频·车载audio·car_service
shuangrenlong6 分钟前
androidstudio gradle文件报红
android
Digitally9 分钟前
如何通过蓝牙将 iPhone 上的照片传输到 Android
android·ios·iphone
常利兵11 分钟前
Android Intent.setAction失效报错排查与修复全方案
android
低调小一18 分钟前
RecyclerView 缓存与复用机制:从一次滑动讲明白(2026 版)
android·recyclerview
耶叶19 分钟前
kotlin的修饰符
android·开发语言·kotlin
l1t23 分钟前
在Android设备上利用Termux安装llama.cpp并启动webui
android·llama
浩宇软件开发28 分钟前
基于Android天气预报应用开发APP
android·java·android studio·android开发
毕设源码-郭学长30 分钟前
【开题答辩全过程】以 基于Android的电子日记APP的设计与实现为例,包含答辩的问题和答案
android
AdMergeX32 分钟前
出海行业热点 | App开发商起诉苹果抄袭;欧盟要求Google开放Android AI权限;Google搜索推AI对话模式;中国小游戏冲上美国游戏总榜;
android·人工智能·游戏