在 Scala/Spark 中将纪元转换为日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33475229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert epoch to datetime in Scala / Spark
提问by Zahiro Mor
I'm converting String representing a DateTime to unix_time (epoch) using :
我正在使用以下方法将表示 DateTime 的 String 转换为 unix_time (epoch):
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 :
得到这样的 Long 列表:
.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 Scalabut can't apply it successfully
我已阅读 Convert seconds since epoch to joda DateTime in Scala但无法成功应用它
采纳答案by Shadowlands
You have a precedence problem - .toDateTimeis being applied to 1000Lbefore *is applied. Bracket the operations to make the call order clear:
您有一个优先级问题 -.toDateTime在应用1000L之前*被应用。括号内使调用顺序清晰的操作:
def timeToStr(x: Long): String = { (x*1000L).toDateTime }
回答by Rahul
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
回答by Zoltán
The opposite of parseDateTimeis print:)
的反面parseDateTime是print:)
def timeToStr(epochMillis: Long): String =
DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss").print(epochMillis)

