我有时间戳的输入,基于我需要使用scala编程减去1秒或零下3个月的某些条件
输入:
val date :String = "2017-10-31T23:59:59.000"
输出:
减1秒
val lessOneSec = "2017-10-31T23:59:58.000"
减去3个月
val less3Mon = "2017-07-31T23:59:58.000"
如何将字符串值转换为Timestamp并在scala编程中执行减号操作?
我假设你正在使用Dataframes,因为你有spark-dataframe标签。
您可以使用SQL INTERVAL来减少时间,但是您的列应该采用timestamp
格式:
df.show(false)
+-----------------------+
|ts |
+-----------------------+
|2017-10-31T23:59:59.000|
+-----------------------+
import org.apache.spark.sql.functions._
df.withColumn("minus1Sec" , date_format($"ts".cast("timestamp") - expr("interval 1 second") , "yyyy-MM-dd'T'HH:mm:ss.SSS") )
.withColumn("minus3Mon" , date_format($"ts".cast("timestamp") - expr("interval 3 month ") , "yyyy-MM-dd'T'HH:mm:ss.SSS") )
.show(false)
+-----------------------+-----------------------+-----------------------+
|ts |minus1Sec |minus3Mon |
+-----------------------+-----------------------+-----------------------+
|2017-10-31T23:59:59.000|2017-10-31T23:59:58.000|2017-07-31T23:59:59.000|
+-----------------------+-----------------------+-----------------------+
请尝试以下代码
val yourDate = "2017-10-31T23:59:59.000"
val formater = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
val date = LocalDateTime.parse(yourDate, formater)
println(date.minusSeconds(1).toString(formater))
println(date.minusMonths(3).toString(formater))
产量
2017-10-31T23:59:58.000
2017-07-31T23:59:59.000
看看jodatime图书馆。它拥有您需要的所有API,从时间戳开始减去秒或数月
http://www.joda.org/joda-time/
sbt依赖
"joda-time" % "joda-time" % "2.9.9"