All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jchanghong.kotlin.Dates.kt Maven / Gradle / Ivy

package jchanghong.kotlin

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.formatterStr(): String {
    return this.format(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)) ?: ""
}

fun Date.formatterStr(): String {
    return DateUtil.formatDateTime(this)
}
fun Any?.formatterStr():String{
   return when (this) {
        is Date->this.formatterStr()
        is LocalDate->this.formatterStr()
        is LocalDateTime->this.formatterStr()
        else ->this.toString()
    }
}

fun LocalDate.formatterStr(): String {
    return this.format(DateTimeFormatter.ofPattern(DATE_PATTERN)) ?: ""
}
fun LocalDateTime.toDate(): Date {
    return Date.from(this.toInstant(ZoneOffset.ofHours(8)))
}
fun LocalDate.toDate(): Date {
    return Date.from(this.atTime(0, 0, 0)
        .toInstant(ZoneOffset.ofHours(8)))
}

fun main() {
    println(LocalDateTime.now().formatterStr())
    println(LocalDate.now().formatterStr())
    println(LocalDateTime.now().toDate().formatterStr())
    println(LocalDate.now().toDate().formatterStr())
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy