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 ""
    }
}
相关推荐
alexhilton5 小时前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
冬奇Lab8 小时前
InputManagerService:输入事件分发与ANR机制
android·源码阅读
张小潇11 小时前
AOSP15 Input专题InputManager源码分析
android·操作系统
RdoZam13 小时前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
奥陌陌18 小时前
android 打印函数调用堆栈
android
用户9851200358318 小时前
Compose Navigation 3 深度解析(二):基础用法
android·android jetpack
恋猫de小郭19 小时前
Android 官方正式官宣 AI 支持 AppFunctions ,Android 官方 MCP 和系统级 OpenClaw 雏形
android·前端·flutter
黄林晴19 小时前
Android 17 Beta 2,隐私这把锁又拧紧了
android
Kapaseker20 小时前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
bqliang20 小时前
Compose 媒体查询 (Media Query API) 🖱️👇🕹️
android·android jetpack