DateHelper.scala 2.47 KB
package tools.timestamp


import java.text.SimpleDateFormat
import java.time.format.{DateTimeFormatter, DateTimeFormatterBuilder}

import java.time.{OffsetDateTime, ZoneId, ZonedDateTime}
import java.util.Date
import scala.language.postfixOps

/**
 * Created with IntelliJ IDEA.
 * Class: DateHelper
 * Description: 时间处理类
 * User: lin
 * Date: 2021-07-19
 * Time: 16:17
 */
object DateHelper {

  private[this] val DATE_TIME_FORMATTER: DateTimeFormatter = new DateTimeFormatterBuilder().appendOptional(DateTimeFormatter.ISO_DATE_TIME).appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME).appendOptional(DateTimeFormatter.ISO_INSTANT).appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX")).appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX")).appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toFormatter.withZone(ZoneId.systemDefault())

  /**
   * 把时间字符串转换成标准时间
   *
   * @param str 时间字符串
   * @return 标准时间
   */
  def parseDateTimeString(str: String): OffsetDateTime = ZonedDateTime.from(DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime

  /**
   * 时间戳转换成时间
   *
   * @param timestamp 时间戳(毫秒)
   * @param pattern   时间格式
   * @return 指定格式的日期
   */
  def parseTimestampToDataTime(timestamp: Long, pattern: String): String = new SimpleDateFormat(pattern).format(new Date(formatTimestamp(timestamp)))

  /**
   * 时间戳转换成时间(默认格式)
   *
   * @param timestamp 时间戳(毫秒)
   * @return 默认格式“yyyy-MM-dd HH:mm:ss”
   */
  def parseTimestampToDataTime(timestamp: Long): String = parseTimestampToDataTime(formatTimestamp(timestamp), "yyyy-MM-dd HH:mm:ss")

  /**
   * 把时间格式定为毫秒,如果不是毫秒 x1000
   *
   * @param timestamp 时间戳
   * @return 格式化时间戳
   */
  def formatTimestamp(timestamp: Long): Long = if (timestamp.toString.length < 13) timestamp * 1000 else timestamp

  /**
   * 把时间转换成时间戳
   *
   * @param time    时间
   * @param pattern 时间格式
   * @return 时间戳
   */
  def parseDateTimeToTimestamp(time: String, pattern: String): Long = new SimpleDateFormat(pattern).parse(time).getTime

  /**
   * 把时间转换成时间戳(默认格式)
   *
   * @param time 时间
   * @return 时间戳(默认格式:”yyyy-MM-dd HH:mm:ss“)
   */
  def parseDateTimeToTimestamp(time: String): Long = parseDateTimeToTimestamp(time, "yyyy-MM-dd HH:mm:ss")

}