You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中Long值转带时分的日期时间及当前时间转Long的实现方法

Kotlin实现时间戳与带时分的日期字符串互转

没问题,我来帮你用Kotlin实现这两个需求,结合你给的原有Code A,咱们一步步来:

1. 扩展Long类型,实现转含日期+时间的字符串

你的原有代码用了DateFormat.getDateInstance只处理日期,现在要同时包含时间,我们可以用getDateTimeInstance(适配系统区域格式),或者自定义固定格式来严格匹配你要的yyyy.MM.dd HH:mm样式,两种方案都给你:

方案一:适配系统区域的日期时间格式

这个函数和你原有的扩展函数风格一致,支持自定义日期、时间的格式级别:

import java.text.DateFormat
import java.util.Locale

fun Long.toDateTimeString(
    dateFormat: Int = DateFormat.MEDIUM,
    timeFormat: Int = DateFormat.SHORT
): String {
    // 同时获取日期+时间的格式化实例
    val df = DateFormat.getDateTimeInstance(dateFormat, timeFormat, Locale.getDefault())
    return df.format(this)
}

方案二:严格匹配指定格式(如2018.01.10 23:11)

如果需要固定输出yyyy.MM.dd HH:mm这种格式,用SimpleDateFormat自定义规则更稳妥:

import java.text.SimpleDateFormat
import java.util.Locale

fun Long.toCustomDateTimeString(): String {
    val sdf = SimpleDateFormat("yyyy.MM.dd HH:mm", Locale.getDefault())
    return sdf.format(this)
}

2. 实现当前时间转Long值(时间戳)

这个需求很简单,直接获取当前时间的毫秒级时间戳即可,有两种常见写法:

// 方式一:Java标准库写法,兼容性好
fun getCurrentTimeAsLong(): Long {
    return System.currentTimeMillis()
}

// 方式二:Kotlinx.datetime库写法(需要先引入kotlinx.datetime依赖)
// import kotlinx.datetime.Clock
// fun getCurrentTimeAsLong(): Long {
//     return Clock.System.now().toEpochMilliseconds()
// }

测试示例

把这些函数放到项目里,用下面的代码测试效果:

fun main() {
    // 测试Long转指定格式的日期时间字符串
    val testTimestamp = 1515589860000L // 对应2018.01.10 23:11
    println(testTimestamp.toCustomDateTimeString()) // 输出:2018.01.10 23:11
    
    // 测试获取当前时间戳并转字符串
    val currentTimestamp = getCurrentTimeAsLong()
    println(currentTimestamp.toCustomDateTimeString()) // 输出当前的日期时间,比如2024.05.20 14:30
}

内容的提问来源于stack exchange,提问作者HelloCW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:48:39