也许这是一个重复的问题,我试图找到解决方案,但没有办法。
问题:将 DateTime 实例转换为 Timestamp。
我的 DateTime 实例创建为:
import org.joda.time.DateTime
val start = (new DateTime).withYear(2016)
.withMonthOfYear(12)
.withDayOfMonth(1)
.withMinuteOfHour(0)
.withHourOfDay(0)
使用这个日期的 println,我得到:
2016-12-01T00:00:18.856+01:00
最佳答案
恕我直言,计算纪元时间戳的最快方法之一是:
scala> :paste
// Entering paste mode (ctrl-D to finish)
def epochDayForYear(year: Int): Long =
365L * year + (((year + 3) >> 2) - (if (year < 0) {
val century = year * 1374389535L >> 37 // divide int by 100 (a sign correction is not required)
century - (century >> 2)
} else ((year + 99) * 1374389535L >> 37) - ((year + 399) * 1374389535L >> 39))) // divide int by 100 and by 400 accordingly (a sign correction is not required)
def dayOfYearForYearMonth(year: Int, month: Int): Int =
((month * 1050835331877L - 1036518774222L) >> 35).toInt - // == (367 * month - 362) / 12
(if (month <= 2) 0
else if (isLeap(year)) 1
else 2)
def isLeap(year: Int): Boolean = (year & 3) == 0 && {
val century = (year * 1374389535L >> 37).toInt - (year >> 31) // divide int by 100
century * 100 != year || (century & 3) == 0
}
def secondOfDay(hour: Int, month: Int, day: Int): Int =
hour * 3600 + month * 60 + day
val (year, month, day, hour, minute, second, timeZoneOffsetHour, timeZoneOffsetMinute) =
(2016, 12, 1, 0, 0, 2, 0, 0)
val epochSecond =
(epochDayForYear(year) + (dayOfYearForYearMonth(year, month) + day - 719529)) * 86400 +
secondOfDay(hour + timeZoneOffsetHour, minute + timeZoneOffsetMinute, second) // where 719528 is days 0000 to 1970
// Exiting paste mode, now interpreting.
epochDayForYear: (year: Int)Long
dayOfYearForYearMonth: (year: Int, month: Int)Int
isLeap: (year: Int)Boolean
secondOfDay: (hour: Int, month: Int, day: Int)Int
year: Int = 2016
month: Int = 12
day: Int = 1
hour: Int = 0
minute: Int = 0
second: Int = 2
timeZoneOffsetHour: Int = 0
timeZoneOffsetMinute: Int = 0
epochSecond: Long = 1480550402
顺便说一句,这段代码的大部分是借自 jsoniter-scala项目。
关于Scala 将 DateTime 值转换为时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53415264/