convert epoch to datetime in Scala / Spark

帅比萌擦擦* 提交于 2020-01-13 14:44:33

问题


I'm converting String representing a DateTime to unix_time (epoch) using :

def strToTime(x: String):Long = { DateTimeFormat.
    forPattern("YYYY-MM-dd HH:mm:ss").parseDateTime(x).getMillis()/1000 }

to get a list of Long like this :

.map( p=> List( strToTime(p(0) ) ) ) 

my question is - what is the easiest way to turn in backwards? something like:

def timeToStr(x: Long):String = { x*1000L.toDateTime}

that I could use on the above List(Long)

I have read Convert seconds since epoch to joda DateTime in Scala but can't apply it successfully


回答1:


You have a precedence problem - .toDateTime is being applied to 1000L before * is applied. Bracket the operations to make the call order clear:

def timeToStr(x: Long): String = { (x*1000L).toDateTime }



回答2:


The opposite of parseDateTime is print :)

def timeToStr(epochMillis: Long): String =
  DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss").print(epochMillis)



回答3:


Follows my approach!

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

def epochToDate(epochMillis: Long): String = {
    val df:SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd")
    df.format(epochMillis)
}   

Follows a test run.

scala> epochToDate(1515027919000L)
res0: String = 2018-01-03


来源:https://stackoverflow.com/questions/33475229/convert-epoch-to-datetime-in-scala-spark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!