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 ""
    }
}
相关推荐
mygljx5 小时前
MySQL 数据库连接池爆满问题排查与解决
android·数据库·mysql
xinhuanjieyi6 小时前
ruoyimate导入sql\antflow\bpm_init_db.sql报错
android·数据库·sql
闲猫7 小时前
基于RABC的权限控制设计
android
星霜笔记11 小时前
GitMob — 手机端 GitHub 管理工具
android·kotlin·github·android jetpack
LiuYaoheng11 小时前
问题记录:Android Studio Low memory
android·ide·android studio
独隅12 小时前
Python 标准库 (Standard Library) 全面使用指南
android·开发语言·python
always_TT12 小时前
strlen、strcpy、strcat等常用字符串函数
android
qqty121712 小时前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
2401_8955213412 小时前
MySQL中between and的基本用法
android·数据库·mysql
云云鬼才13 小时前
CoCo编辑器、图形化编程怎么调用Scheme(跳转应用)
android