一起来学Kotlin:概念:10. Kotlin Dates 两种表现方式介绍
此文档介绍Kotlin Dates的两种书写方式。
这里先把相关的代码附上,我们可以在kotlin playground上直接运行:
import java.text.SimpleDateFormat
import java.util.*
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.Period
/**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main() {
println("First way of showing date time.")
val timeNow = Calendar.getInstance().time.time
println("current time in long: ${timeNow}")
val dateTimeNow = dateAsString(timeNow)
println("current time in date format: ${dateTimeNow}")
val dateTime1DayAgo = dateAsString(timeNow-1000*60*60*24)
println("Time 1 day ago in date format: ${dateTime1DayAgo}")
println("Second way of showing date time.")
val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
val date = LocalDate.parse("31-12-2018", formatter)
println("specific time in date format: ${date}.")
val dateInString = date.toString()
println("specific time in string: ${date}.")
val period = Period.of(1, 2, 3) // This creates a Period of 1 year, 2 months and 3 days.
val modifiedDate = date.plus(period)
println("Time after adding 1 year, 2 months, 3 days, in date format: ${modifiedDate}.")
val modifiedDateMinus = date.plus(period)
println("Time after minusing 1 year, 2 months, 3 days, in date format: ${modifiedDateMinus}.")
val date1 = LocalDate.parse("2018-06-25")
val date2 = LocalDate.parse("2018-12-25")
val period2 = Period.between(date1, date2)
println("Time between date1 and date2 is: ${period2}.") // P stands for Period and 6M means 6 months.
}
fun dateAsString(
dateInMillis: Long,
format: String = "dd.MM.yyyy HH:mm",
locale: Locale = Locale.getDefault()
): String {
val date = Date(dateInMillis)
val formatter = SimpleDateFormat(format, locale)
return formatter.format(date)
}
返回:
First way of showing date time.
current time in long: 1663254528651
current time in date format: 15.09.2022 15:08
Time 1 day ago in date format: 14.09.2022 15:08
Second way of showing date time.
specific time in date format: 2018-12-31.
specific time in string: 2018-12-31.
Time after adding 1 year, 2 months, 3 days, in date format: 2020-03-03.
Time after minusing 1 year, 2 months, 3 days, in date format: 2020-03-03.
Time between date1 and date2 is: P6M.
第一种 Dates
的使用方式是通过 Calendar
。需要注意的是,Calendar.getInstance().time.time
返回的是一个long
的值。对应的数值很大,因为精确到millisecond。所以,当我们需要计算几天前几天后的某一个时间点时,只需要加减对应millisecond的值即可。dateAsString
函数的作用是将Long
格式的时间转化为"dd.MM.yyyy HH:mm"
格式,方便在界面显示。我个人比较喜欢这一种时间的使用方式,方便存储,也方便显示。
第二种 Dates
的使用方式是通过 LocalDate
。详细的使用方式参见上面的代码。这种方式也是比较简单直白的。