jchanghong.kotlin.Dates.kt Maven / Gradle / Ivy
package jchanghong.kotlin
import cn.hutool.core.date.DateTime
import cn.hutool.core.date.DateUtil
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.*
const val DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"
const val DATE_PATTERN = "yyyy-MM-dd"
/**
\* Created with IntelliJ IDEA.
\* User: jiang
\* Date: 2020/1/5
\* Time: 11:02
\*/
fun LocalDateTime?.toStr(): String {
this?:return DateUtil.now()
return this.format(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)) ?: ""
}
fun Date?.toStr(): String {
this?:return DateUtil.now()
return DateUtil.formatDateTime(this)
}
fun Any?.toStr():String{
return when (this) {
is Date->this.toStr()
is LocalDate->this.toStr()
is LocalDateTime->this.toStr()
else ->this.toString()
}
}
fun LocalDate?.toStr(): String {
this?:return DateUtil.today()
return this.format(DateTimeFormatter.ofPattern(DATE_PATTERN)) ?: ""
}
fun LocalDateTime?.toDate(): Date {
this?:return Date()
return Date.from(this.toInstant(ZoneOffset.ofHours(8)))
}
fun LocalDate?.toDate(): Date {
this?:return Date()
return Date.from(this.atTime(0, 0, 0)
.toInstant(ZoneOffset.ofHours(8)))
}
fun Date?.toLocalDateTime(): LocalDateTime {
this?:return LocalDateTime.now()
return LocalDateTime.parse(this.toStr(),DateTimeFormatter.ofPattern(DATE_TIME_PATTERN))
}
fun String?.toLocalDateTime(): LocalDateTime {
this?:return LocalDateTime.now()
return try {
val dateTime: DateTime? = DateUtil.parse(this)
dateTime.toLocalDateTime()
} catch (e: Exception) {
LocalDateTime.now()
}
}
fun main() {
println(DateUtil.now().toLocalDateTime().toStr())
println(Date().toLocalDateTime().toStr())
println(LocalDateTime.now().toStr())
println(LocalDate.now().toStr())
println(LocalDateTime.now().toDate().toStr())
println(LocalDate.now().toDate().toStr())
}