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 ""
    }
}
相关推荐
程序员陆业聪3 小时前
Android 平台 AI Agent 技术架构深度解析
android·人工智能
BD_Marathon9 小时前
工厂方法模式
android·java·工厂方法模式
王码码20359 小时前
Flutter for OpenHarmony:socket_io_client 实时通信的事实标准(Node.js 后端的最佳拍档) 深度解析与鸿蒙适配指南
android·flutter·ui·华为·node.js·harmonyos
勇气要爆发10 小时前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain
Railshiqian10 小时前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript
恋猫de小郭11 小时前
Flutter 的真正价值是什么?深度解析再结合鸿蒙,告诉你 Flutter 的真正优势
android·前端·flutter
Ehtan_Zheng11 小时前
我们如何在不减少功能的前提下,将安卓应用体积缩减 60%
android
QING61812 小时前
使用ADB分析CPU性能 —— 基础指南
android·前端·app
大白要努力!12 小时前
Android图片预览功能实战:从需求到上线的完整方案
android·viewpager·图片预览·实战记录·photoview
如此风景15 小时前
kotlin协程学习小计
android·kotlin