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 ""
    }
}
相关推荐
2501_915921431 小时前
苹果iOS应用开发上架与推广完整教程
android·ios·小程序·https·uni-app·iphone·webview
jian110582 小时前
Android studio gradle和插件的版本设置
android·ide·android studio
idolao2 小时前
Android Studio 2022安装与汉化教程 Windows版:解压+管理员运行+自定义路径+SDK配置+中文插件指南
android·windows·android studio
2501_915106322 小时前
HTTP和HTTPS协议工作原理及安全性全面解析
android·ios·小程序·https·uni-app·iphone·webview
古阙月2 小时前
嘉立创PCB设计初级总结
android·pcb工艺
Dream of maid2 小时前
Mysql(7)子查询
android·数据库·mysql
恋猫de小郭3 小时前
compose_skill 和 android skills,对 Android 项目提升巨大的专家 AI Skills
android·前端·flutter
我命由我123453 小时前
Android Jetpack Compose - ModalNavigationDrawer、NavigationRail、PullToRefreshBox
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
侠客工坊3 小时前
大模型落地移动端:解析侠客工坊端侧 Agent 的零拷贝(Zero-Copy)屏幕感知与空间映射
android·人工智能