scala 时间格式转换(String、Long、Date)

时间:2022-09-13 11:28:43

1)scala 时间格式转换(String、Long、Date)

1、时间字符类型转Date类型

[java] view plain copy
import java.text.SimpleDateFormat 
val time = "2017-12-18 00:01:56" 
val newtime :Date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time) 
println(newtime) 
//output:Mon Dec 18 00:01:56 CST 2017

2、Long类型转字符类型

[java] view plain copy
val time:Long= 1513839667//
val newtime :String = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time*1000) 
println(newtime) 
//output:2017-12-21 15:01:07 

3、时间字符类型转Long类型

[java] view plain copy
val time = "2017-12-18 00:01:56" 
val newtime :Long= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time).getTime 
println(newtime) 
//output:1513526516000

 

2)scala 时间和时间戳互转

时间转换为时间戳:

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
}
}