在Scala / Spark中将epoch转换为datetime

问题描述 投票:2回答:3

我正在使用以下代码将表示DateTime的String转换为unix_time(epoch):

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

得到这样的Long列表:

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

我的问题是 - 倒退的最简单方法是什么?就像是:

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

我可以在上面的列表中使用(长)

我已阅读Convert seconds since epoch to joda DateTime in Scala但无法成功应用

scala datetime apache-spark jodatime
3个回答
3
投票

你有一个优先问题 - 在应用.toDateTime之前,1000L正被应用于*。对操作进行括号以使呼叫顺序清晰:

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

4
投票

parseDateTime的反面是print :)

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

2
投票

按照我的方法!

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

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

按照测试运行。

scala> epochToDate(1515027919000L)
res0: String = 2018-01-03
© www.soinside.com 2019 - 2024. All rights reserved.