scala时间和时间戳互转

时间:2021-04-10 02:28:35

时间转换为时间戳:

import java.text.SimpleDateFormat

object test {

  def main(args: Array[String]): Unit = {

    val tm = "2017-08-01 16:44:32"
    val a = tranTimeToLong(tm)
    println(a)
  }

  def tranTimeToLong(tm:String) :Long={
    val fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val dt = fm.parse(tm)
    val aa = fm.format(dt)
    val tim: Long = dt.getTime()
    tim
  }
}

时间戳转化为时间:

import java.text.SimpleDateFormat
import java.util.Date

object test {

  def main(args: Array[String]): Unit = {

    val tm = "1502036122000"
    val a = tranTimeToString(tm)
    println(a)

  }

  def tranTimeToString(tm:String) :String={
    val fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val tim = fm.format(new Date(tm.toLong))
    tim
  }
}