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 ""
    }
}
相关推荐
安小牛22 分钟前
Android 开发汉字转带声调的拼音
android·java·学习·android studio
聚美智数23 分钟前
企业实际控制人查询-公司实控人查询
android·java·javascript
JMchen1232 小时前
第 3 篇|Android 项目结构解析与第一个界面 —— Hello, CSDN!
android·android studio·android 零基础·android 项目结构·android 界面开发
众少成多积小致巨5 小时前
Soong构建入门
android·go·编译器
笔夏5 小时前
【安卓学习之混淆】记录一些混淆导致闪退
android·学习
阿巴斯甜5 小时前
Kotlin高阶函数和Java 8 lambda的区别:
android
张小潇5 小时前
AOSP15 WMS/AMS系统开发 - WindowManagerService relayout调用流程详解
android
阿巴斯甜5 小时前
Kotlin 高阶函数:
android
之歆6 小时前
Day03_HTML 列表、表格、表单完整指南(下)
android·javascript·html
QING6186 小时前
Kotlin之【init】—— 新手须知
android·kotlin·android jetpack