【问题标题】:convert epoch to datetime in Scala / Spark在 Scala / Spark 中将纪元转换为日期时间
【发布时间】:2018-01-04 11:02:39
【问题描述】:

我正在使用以下方法将表示 DateTime 的字符串转换为 unix_time(纪元):

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}

我可以在上面的 List(Long) 上使用

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

【问题讨论】:

  • 您只需要在 x*1000L 左右放置大括号。即(x*1000L).toDateTime.

标签: scala datetime apache-spark jodatime


【解决方案1】:

按照我的方法!

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

【讨论】:

    【解决方案2】:

    您有一个优先级问题 - 在应用 * 之前,.toDateTime 被应用到 1000L。括号中的操作使调用顺序清晰:

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

    【讨论】:

    • 不适合我:我错过了图书馆还是什么?我已经导入: import org.joda.time.format._ import org.joda.time._ 但仍然得到 scala> def timeToStr(x: Long):String = { (x*1000L).toDateTime} : 31:错误:值 toDateTime 不是 Long 的成员
    • @ZahiroMor 啊,我猜你已经设置了一个合适的“toDateTime”“pimp my library”扩展(例如,使用隐式转换)——比如:implicit class ToDateTime(millis: Long) { def toDateTime = DateTime(millis) }
    【解决方案3】:

    parseDateTime 的反义词是print :)

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

    【讨论】:

    • 我想你的意思是def timeToStr(epochMillis: Long):String =
    • 你真的收到291 好几天了?看起来您的格式化程序字符串中可能有错字。特别是,您似乎正在使用"YYYY-MM-dd1 HH:mm:ss"
    • 实际上几天都是 DD 而不是 dd。我的错。
    猜你喜欢
    • 2018-04-24
    • 2011-12-06
    • 2012-09-06
    • 2012-11-08
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2016-09-15
    相关资源
    最近更新 更多