Kotlin中如何将System.currentTimeMillis()转换为指定日期格式
Kotlin实现时间戳格式化与数据库存储格式转换
1. 将当前毫秒级时间戳转为dd-mm-yyyy HH:MM:SS格式
推荐使用Java 8+引入的java.time包API(线程安全,替代过时的Date/SimpleDateFormat),实现代码如下:
import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter fun formatCurrentTimestamp(): String { val timestamp = System.currentTimeMillis() // 将毫秒级时间戳转为Instant,再转换为指定时区的时间 val instant = Instant.ofEpochMilli(timestamp) val zoneId = ZoneId.systemDefault() // 可替换为业务时区,比如ZoneId.of("Asia/Shanghai") val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss") return formatter.format(instant.atZone(zoneId)) } // 调用示例 fun main() { println(formatCurrentTimestamp()) // 输出示例:15-03-2023 11:32:44 }
2. 将数据库秒级时间戳转为yyyy-mm-dd格式存储
数据库中存储的是秒级时间戳(如1678962531),提供两种适配场景的实现:
方式1:转换为yyyy-MM-dd字符串
适合需要以字符串格式存入数据库的场景:
import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter fun convertTimestampToDbDateString(secondsTimestamp: Long): String { // 秒级时间戳转Instant val instant = Instant.ofEpochSecond(secondsTimestamp) val zoneId = ZoneId.systemDefault() // 指定业务对应时区 val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") return formatter.format(instant.atZone(zoneId).toLocalDate()) } // 调用示例 fun main() { val dbTimestamp = 1678962531L println(convertTimestampToDbDateString(dbTimestamp)) // 输出:2023-03-15 }
方式2:直接转换为LocalDate类型(推荐)
如果数据库驱动支持JDBC 4.2+,可直接将LocalDate对象存入DATE类型字段,无需转字符串:
import java.time.Instant import java.time.ZoneId fun convertTimestampToLocalDate(secondsTimestamp: Long): java.time.LocalDate { val instant = Instant.ofEpochSecond(secondsTimestamp) val zoneId = ZoneId.systemDefault() return instant.atZone(zoneId).toLocalDate() }
注意事项
- 必须指定业务对应的时区,避免时区差异导致日期转换错误;
- 禁止使用过时的
Date和SimpleDateFormat类,它们存在线程安全隐患。
内容的提问来源于stack exchange,提问作者Akshay Prakash
相关产品推荐
相关产品推荐

