开发中经常要将日期格式进行转换,下面是自己日常开发中常用的基于jdk8日期格式转换工具类
package com.ops
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter
import java.time.temporal.{ChronoUnit, TemporalAccessor}
import java.time._
import java.util.{Calendar, Date, Locale, TimeZone}
object DateUtil {
def main(args: Array[String]): Unit = {
//不带杠日期时间转带杠日期时间,输入必须带时分秒
println(dateTimeFormatWithHyphenJdk8("20191012 10:12:10")) //2019-10-12 10:12:10
//带杠日期时间转不带杠日期时间,输入必须带时分秒
println(dateTimeFormatWithNoHyphenJdk8("2019-10-12 10:00:12")) //20191012 10:00:12
//日期时间转时间戳(毫秒),输入必须带时分秒
println(dateTimeToTimestampJdk8("2019-10-12 10:00:12")) //1570845612000
println(dateTimeToTimestampJdk8("20191012 10:00:12")) //1570845612000
//时间戳转日期时间,true带杠,false不带杠
println(timeStampTodateTimeJdk8(1570845612000L, isHyphen = true)) //2019-10-12 10:00:12
println(timeStampTodateTimeJdk8(1570845612000L, isHyphen = false)) //20191012 10:00:12
//日期时间加(year,month,day,hour,minute,second)正数为+ 负数为- true传出带杠日期,false传出不带带杠日期,输入必须带时分秒
println(dateTimeAddJdk8("2019-10-12 10:00:12", "hour", -13, isOutputHyphen = true)) //2019-10-11 21:00:12
println(dateTimeAddJdk8("20191012 10:00:12", "hour", -13, isOutputHyphen = false)) //20191011 21:00:12
//日期相减得到(天,小时,分钟,秒,毫秒的tuple),输入必须带时分秒
println(dateTimeSubstractJdk8("20191012 10:00:12", "20191014 11:00:11")) //(2,48,2939,176399,176399000)
println(dateTimeSubstractJdk8("2019-10-12 10:00:12", "2019-10-14 11:00:11")) //(2,48,2939,176399,176399000)
//将日期时间各部分分割出来(年,月,日,小时,分钟,秒的tuple),输入必须带时分秒
println((getPartOfDateTimeJdk8("2019-01-12 10:00:12"), getPartOfDateTimeJdk8("20191012 10:00:12"))) //((2019,01,12,10,00,12),(2019,10,12,10,00,12))
//获取当前日期true带杠,false不带杠
println((getCurrentDateJdk8(true), getCurrentDateJdk8(false))) //(2019-11-23,20191123)
//获取当前日期时间 true带杠,false不带杠
println((getCurrentDateTimeJdk8(true), getCurrentDateTimeJdk8(false))) //(2019-11-23 20:24:30,20191123 20:24:30)
//获取年月日日期, false输出不带杠日期,true输出带杠日期,输入可以带时分秒,也可以不带
println((getDateJdk8("2019-01-12 10:00:12", isHyphen = false), getDateJdk8("20191014 11:00:11", isHyphen = true))) //(20190112,2019-10-14)
//获取当前时间戳秒
println(getCurrentTimestampJdk8) //1574511870
//获取当前时间戳毫秒
println(getCurrentTimestampMillsJdk8) //1574511870056
//utc转本地时间格式
println(dateFormatUTC2Local("2020-07-03T08:20:41.283Z"))
}
val df = new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.getDefault)
val df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault)
val calendar = Calendar.getInstance()
df.setLenient(false)
df1.setLenient(false)
val df2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val df3 = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss")
val zone = ZoneId.systemDefault()
def getCurrentTimestampJdk8: Long = {
LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))
}
def getCurrentTimestampMillsJdk8: Long = {
LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()
}
def getDateJdk8(input: String, isHyphen: Boolean): String = {
input.contains("-") match {
case true => if (isHyphen) input.substring(0, 10) else input.substring(0, 10).replaceAll("-", "")
case false => if (isHyphen) input.substring(0, 4) + "-" + input.substring(4, 6) + "-" + input.substring(6, 8) else input.substring(0, 8)
}
}
def getCurrentDateJdk8(isHyphen: Boolean): String = {
val localDate = LocalDate.now()
val date = localDate.toString
if (isHyphen)
date
else
date.replaceAll("-", "")
}
def getCurrentDateTimeJdk8(isHyphen: Boolean): String = {
val dateTime = LocalDateTime.now().withNano(0).toString.replace("T", " ")
if (isHyphen)
dateTime
else
dateTimeFormatWithNoHyphenJdk8(dateTime)
}
//输入带杠日期,输出不带杠日期
def dateTimeFormatWithHyphenJdk8(input: String): String = {
val date = df3.parse(input)
df2.format(date)
}
//输入不带杠日期,输出带杠日期
def dateTimeFormatWithNoHyphenJdk8(input: String): String = {
val date = df2.parse(input)
df3.format(date)
}
def dateTimeToTimestampJdk8(input: String): Long = {
input.contains("-") match {
case true => val date = df2.parse(input)
val localDateTime = LocalDateTime.parse(df3.format(date), df3)
val instant = localDateTime.atZone(zone).toInstant
instant.toEpochMilli
case false => val date = df3.parse(input)
val localDateTime = LocalDateTime.parse(df2.format(date), df2)
val instant = localDateTime.atZone(zone).toInstant
instant.toEpochMilli
}
}
def dateTimeToTimestamp(input: String): Long = {
input.contains("-") match {
case true => df1.parse(input).getTime
case false => df.parse(input).getTime
}
}
def timeStampTodateTime(input: Long, isHyphen: Boolean): String = {
isHyphen match {
case true => df1.format(new Date(input))
case false => df.format(new Date(input))
}
}
def timeStampTodateTimeJdk8(input: Long, isHyphen: Boolean): String = {
val instant = Instant.ofEpochMilli(input)
val localDateTime = LocalDateTime.ofInstant(instant, zone)
isHyphen match {
case true => df2.format(localDateTime)
case false => df3.format(localDateTime)
}
}
def dateTimeAdd(input: String, intervalType: String, interval: Int, isOutputHyphen: Boolean): String = {
calendar.setTime(df1.parse(input))
intervalType match {
case "year" => calendar.add(Calendar.YEAR, interval)
case "month" => calendar.add(Calendar.MONTH, interval)
case "date" => calendar.add(Calendar.DATE, interval)
case "hour" => calendar.add(Calendar.HOUR, interval)
case "minute" => calendar.add(Calendar.MINUTE, interval)
case "second" => calendar.add(Calendar.SECOND, interval)
}
val outPutDateTime = df.format(new Date(calendar.getTimeInMillis))
isOutputHyphen match {
case true => outPutDateTime
case false => dateTimeFormatWithNoHyphenJdk8(outPutDateTime)
}
}
def dateTimeAddJdk8(input: String, intervalType: String, interval: Int, isOutputHyphen: Boolean): String = {
var date: TemporalAccessor = null
input.contains("-") match {
case true => date = df2.parse(input)
case false => date = df3.parse(input)
}
val localDateTime = LocalDateTime.parse(df3.format(date), df3)
val afterLocalDateTime = intervalType match {
case "year" => localDateTime.plusYears(interval)
case "month" => localDateTime.plusMonths(interval)
case "date" => localDateTime.plusDays(interval)
case "hour" => localDateTime.plusHours(interval)
case "minute" => localDateTime.plusMinutes(interval)
case "second" => localDateTime.plusSeconds(interval)
}
isOutputHyphen match {
case true => df2.format(afterLocalDateTime)
case false => df3.format(afterLocalDateTime)
}
}
def dateTimeSubstract(inputBiggerDate: String, inputSmallerDate: String): (String, String, String, String, String) = {
val biggerTimestamp = df.parse(inputBiggerDate).getTime
val smallerTimestamp = df.parse(inputSmallerDate).getTime
val intervalMillis = biggerTimestamp - smallerTimestamp
val intervalSeconds = intervalMillis / 1000
val intervalMinuts = intervalSeconds / 60
val intervalHours = intervalSeconds / 60
val intervalDays = intervalHours / 24
(intervalDays.toString, intervalHours.toString, intervalMinuts.toString, intervalSeconds.toString, intervalMillis.toString)
}
def dateTimeSubstractJdk8(inputBiggerDate: String, inputSmallerDate: String): (String, String, String, String, String) = {
var biggerDateAcc: TemporalAccessor = null
var smallerDateAcc: TemporalAccessor = null
inputBiggerDate.contains("-") match {
case true => biggerDateAcc = df2.parse(inputBiggerDate)
smallerDateAcc = df2.parse(inputSmallerDate)
case false => biggerDateAcc = df3.parse(inputBiggerDate)
smallerDateAcc = df3.parse(inputSmallerDate)
}
val localInputBiggerDate = LocalDateTime.parse(df3.format(biggerDateAcc), df3)
val localInputSmallerDate = LocalDateTime.parse(df3.format(smallerDateAcc), df3)
val intervalDays = ChronoUnit.DAYS.between(localInputBiggerDate, localInputSmallerDate)
val intervalHours = ChronoUnit.HOURS.between(localInputBiggerDate, localInputSmallerDate)
val intervalMinutes = ChronoUnit.MINUTES.between(localInputBiggerDate, localInputSmallerDate)
val intervalSeconds = ChronoUnit.SECONDS.between(localInputBiggerDate, localInputSmallerDate)
val intervalMillis = ChronoUnit.MILLIS.between(localInputBiggerDate, localInputSmallerDate)
(intervalDays.toString, intervalHours.toString, intervalMinutes.toString, intervalSeconds.toString, intervalMillis.toString)
}
def getPartOfDateTime(input: String): (String, String, String, String, String, String) = {
calendar.setTime(df1.parse(input))
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val date = calendar.get(Calendar.DATE)
val hour = calendar.get(Calendar.HOUR)
val minute = calendar.get(Calendar.MINUTE)
val second = calendar.get(Calendar.SECOND)
(year.toString,
if (month < 10) s"0${month.toString}" else month.toString,
if (date < 10) s"0${date.toString}" else date.toString,
if (hour < 10) s"0${hour.toString}" else hour.toString,
if (minute < 10) s"0${minute.toString}" else minute.toString,
if (second < 10) s"0${second.toString}" else second.toString
)
}
def getPartOfDateTimeJdk8(input: String): (String, String, String, String, String, String) = {
var dateAcc: TemporalAccessor = null
input.contains("-") match {
case true => dateAcc = df2.parse(input)
case false => dateAcc = df3.parse(input)
}
val localDateTime = LocalDateTime.parse(df3.format(dateAcc), df3)
val year = localDateTime.getYear
val month = localDateTime.getMonth.getValue
val date = localDateTime.getDayOfMonth
val hour = localDateTime.getHour
val minute = localDateTime.getMinute
val second = localDateTime.getSecond
(year.toString,
if (month < 10) s"0${month.toString}" else month.toString,
if (date < 10) s"0${date.toString}" else date.toString,
if (hour < 10) s"0${hour.toString}" else hour.toString,
if (minute < 10) s"0${minute.toString}" else minute.toString,
if (second < 10) s"0${second.toString}" else second.toString
)
}
def dateFormatUTC2Local(utcTime: String): String = {
// val utcTime = "2018-08-28T06:34:33.211Z"
val df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
df.setTimeZone(TimeZone.getTimeZone("UTC"))
// System.out.println(df.parse("2014-08-23T09:20:05Z").toString());
val after = df.parse(utcTime)
df.applyPattern("yyyy-MM-dd HH:mm:ss")
import java.util.TimeZone
df.setTimeZone(TimeZone.getDefault)
df.format(after)
}
def dateFormat(dateStr: String): String = {
val df = new SimpleDateFormat("yyyyMMdd", Locale.getDefault)
val df1 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault)
dateStr.contains("-") match {
case false =>
df.setLenient(false)
df1.format(df.parse(dateStr))
case true =>
df1.setLenient(false)
df.format(df1.parse(dateStr))
}
}
}