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 ""
    }
}
相关推荐
Nerve2 分钟前
GooglePay: 消耗商品购买流程
android·google
LiteHeaven15 分钟前
Android 8.1 Unable to create application data 问题分析
android
Nerve35 分钟前
GooglePay: 一个基于 Google Play Billing Library 封装的 Android 支付库
android·google
Nerve1 小时前
Google Play 结算系统入门指南
android·google
青莲8431 小时前
Android Jetpack - 2 ViewModel
android·前端
3***g2051 小时前
SQLyog安装配置(注册码)连接MySQL
android·mysql·adb
Embedded-Xin2 小时前
Linux架构优化——spdlog实现压缩及异步写日志
android·linux·服务器·c++·架构·嵌入式
萑澈3 小时前
更换SIM卡前必看:如何使用ADB导出并筛选指定SIM卡的全部短信
android
希侬3 小时前
Cursor生成APK加固签名脚本
android