【问题标题】:How can I convert a Long value to date time and convert current time to Long kotlin?如何将 Long 值转换为日期时间并将当前时间转换为 Long kotlin?
【发布时间】:2018-03-29 08:36:38
【问题描述】:

代码 A 可以将 long 值转换为日期值,就像 2018.01.10

  1. 希望得到Date + Time的值,比如2018.01.10 23:11,Kotlin怎么办?

  2. 我希望将当前时间转换为长值,我该如何使用 Kotlin?

谢谢!

代码 A

fun Long.toDateString(dateFormat: Int =  DateFormat.MEDIUM): String {
    val df = DateFormat.getDateInstance(dateFormat, Locale.getDefault())
    return df.format(this)
}

【问题讨论】:

标签: android kotlin


【解决方案1】:

试试这个,我用的是 SimpleDataFormat。

fun convertLongToTime(time: Long): String {
    val date = Date(time)
    val format = SimpleDateFormat("yyyy.MM.dd HH:mm")
    return format.format(date)
}

fun currentTimeToLong(): Long {
    return System.currentTimeMillis()
}

fun convertDateToLong(date: String): Long {
    val df = SimpleDateFormat("yyyy.MM.dd HH:mm")
    return df.parse(date).time
}

使用 Android Studio 将 java 文件转换为 kotlin 文件,选择Code->Convert java file to kotlin file.

【讨论】:

    【解决方案2】:

    不需要任何复杂的东西:

    Date 对象的形式获取当前时间和日期

    val dateTime: Date = Calendar.getInstance().time
    

    将其转换为Long

    val dateTimeAsLong: Long = dateTime.time
    

    Long 转换回 Date

    val backToDate: Date = Date(dateTimeAsLong)
    

    【讨论】:

      猜你喜欢
      • 2012-04-30
      • 2013-07-26
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 2018-04-25
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多