给定小时、月份和年份,将其转换为 Spark scala 中的时间戳

Given hours and month and year, convert it to a time stamp in Spark scala

我有三列 - "Year"、"Month" 和 "Hour"。我需要将其转换为 spark scala 中的时间戳的输入。

示例:我的年份是 2017,月份是 11,小时是 570,我需要将其转换为 Spark Scala 中的时间戳。

对此的任何意见都会有很大帮助。输出应该是 2017-11-23 17:00

Java 的 LocalDateTime 应该为你做这件事

import java.time.LocalDateTime
val y = 2017
val m = 11
val h = 570
val d1 = LocalDateTime.of(y, m, 1, 0, 0) // have to use 1 for day
val d2 = d1.plusHours(h)

不过我得到的结果确实与你不同。以上让我:

d2: java.time.LocalDateTime = 2017-11-24T18:00

    def getTimeStamp(y:Int,m:Int,h:Int) = {
     require(m<=12,"Invalid Data")
     def leapYr(y:Int) = if(y%100==0) y%400==0 else y%4==0
     val monthDays = Array((1,31),(2,28),(3,31),(4,30),(5,31),(6,30),
                            (7,31),(8,31),(9,30),(10,31),(11,30),(12,31))
     val monthDaysLeap = Array((1,31),(2,29),(3,31),(4,30),(5,31),(6,30),
                            (7,31),(8,31),(9,30),(10,31),(11,30),(12,31))
     val days = if(!leapYr(y)){ monthDays(m-1)._2} else { monthDaysLeap(m-1)._2 }
     val hoursInMonth = days*24
     if(h<=hoursInMonth){ val d:Double = h/24.0; val d1=d.toInt;
          val hr = (24*(d-d1)).toInt; y+"-"+m+"-"+d1+" "+hr+":"+"00" 
     }
     else "Invalid Data"
    }

测试:

scala> getTimeStamp(2017,11,570)
res36: String = 2017-11-23 18:00