【时间日期转换】将日期或者时间戳转换成指定格式的字符串并指定时区(Scala实现)

/**
   * Formats a time in milliseconds into a specific pattern in a time zone.
   *
   * @param millis     the time expressed in milliseconds
   * @param pattern    the pattern to use to format the date
   * @param timeZoneId the time-zone ID
   */
  def formatTimeMillis(millis: Long, pattern: String = "yyyy-MM-dd HH:mm:ss", timeZoneId: String = TimeZone.getDefault.getID) = {

    val zoneId = ZoneId.of(StringUtils.trim(timeZoneId))

    val timeZone = TimeZone.getTimeZone(zoneId)

    DateFormatUtils.format(millis, pattern, timeZone)
  }

  /**
   * Formats a date into a specific pattern in a time zone.
   *
   * @param date       – the date to format, not null
   * @param pattern    the pattern to use to format the date
   * @param timeZoneId the time-zone ID
   */
  def formatDate(date: Date, pattern: String = "yyyy-MM-dd HH:mm:ss", timeZoneId: String = TimeZone.getDefault.getID) = {

    val zoneId = ZoneId.of(StringUtils.trim(timeZoneId))

    val timeZone = TimeZone.getTimeZone(zoneId)

    DateFormatUtils.format(date, pattern, timeZone)
  }
  • formatTimeMillis方法是将给定的以毫秒为单位的时间戳,转换为指定格式的时间字符串(默认格式为 yyyy-MM-dd HH:mm:ss)和指定时区Id(默认为系统当前时区Id)的时间字符串。
  • formatDate 方法是将给定的以日期,转换为指定格式的时间字符串(默认格式为 yyyy-MM-dd HH:mm:ss)和指定时区Id(默认为系统当前时区Id)的时间字符串。

下面是测试方法

    println("================formatDate=======================")

    val date = new Date()

    val formatDate1 = formatDate(date, pattern)
    val formatDate2 = formatDate(date, pattern, "Asia/Shanghai")
    val formatDate3 = formatDate(date, pattern, "US/Pacific")
    val formatDate4 = formatDate(date, pattern, "Australia/Brisbane")
    val formatDate5 = formatDate(date, pattern, "Europe/London")

    println(formatDate1)
    println(formatDate2)
    println(formatDate3)
    println(formatDate4)
    println(formatDate5)

    println("==================formatTimeMillis=====================")

    val currentTimeMillis = System.currentTimeMillis()

    val formatTimeMillis1 = formatTimeMillis(currentTimeMillis, pattern)
    val formatTimeMillis2 = formatTimeMillis(currentTimeMillis, pattern, "Asia/Shanghai")
    val formatTimeMillis3 = formatTimeMillis(currentTimeMillis, pattern, "US/Pacific")
    val formatTimeMillis4 = formatTimeMillis(currentTimeMillis, pattern, "Australia/Brisbane")
    val formatTimeMillis5 = formatTimeMillis(currentTimeMillis, pattern, "Europe/London")

    println(formatTimeMillis1)
    println(formatTimeMillis2)
    println(formatTimeMillis3)
    println(formatTimeMillis4)
    println(formatTimeMillis5)

输出结果为:

================formatDate=======================
2023-04-06 15:48:20
2023-04-06 15:48:20
2023-04-06 00:48:20
2023-04-06 17:48:20
2023-04-06 08:48:20
==================formatTimeMillis=====================
2023-04-06 15:48:20
2023-04-06 15:48:20
2023-04-06 00:48:20
2023-04-06 17:48:20
2023-04-06 08:48:20

你可能感兴趣的:(#,时间日期操作,scala,时间转字符串,时区)