在 Scala 中将 org.joda.time.LocalDateTime 转换为 java.time.LocalDateTime 的最准确方法是什么?
What is the most accurate way to convert org.joda.time.LocalDateTime to java.time.LocalDateTime in scala?
我有一个库函数的输出,returns 一个随机的 org.joda.time.LocalDateTime
将来需要转换为 java.time.LocalDateTime
。
在 Scala 中执行此操作而不损失准确性的最有效方法是什么?
看看两者的javadoc,然后想办法创建一个java.time.LocalDateTime
from the getter methods of org.joda.time.LocalDateTime
。
首先,意识到org.joda.time.LocalDateTime
不支持nano-second精度:
Internally, LocalDateTime uses a single millisecond-based value to represent the local datetime. This value is only used internally and is not exposed to applications.
因此,要创建 java.time.LocalDateTime
,请使用 LocalDateTime.of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
。
要从 org.joda.time.LocalDateTime
获取值,请使用:
getYear()
getMonthOfYear()
getDayOfMonth()
getHourOfDay()
getMinuteOfHour()
getSecondOfMinute()
getMillisOfSecond()
就这么简单:阅读文档。
import java.time.ZoneId
val jodaLocalDateTime = org.joda.time.LocalDateTime.now()
val javaLocalDateTime = java.time.LocalDateTime.ofInstant(jodaLocalDateTime.toDate.toInstant, ZoneId.systemDefault())
我有一个库函数的输出,returns 一个随机的 org.joda.time.LocalDateTime
将来需要转换为 java.time.LocalDateTime
。
在 Scala 中执行此操作而不损失准确性的最有效方法是什么?
看看两者的javadoc,然后想办法创建一个java.time.LocalDateTime
from the getter methods of org.joda.time.LocalDateTime
。
首先,意识到org.joda.time.LocalDateTime
不支持nano-second精度:
Internally, LocalDateTime uses a single millisecond-based value to represent the local datetime. This value is only used internally and is not exposed to applications.
因此,要创建 java.time.LocalDateTime
,请使用 LocalDateTime.of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
。
要从 org.joda.time.LocalDateTime
获取值,请使用:
getYear()
getMonthOfYear()
getDayOfMonth()
getHourOfDay()
getMinuteOfHour()
getSecondOfMinute()
getMillisOfSecond()
就这么简单:阅读文档。
import java.time.ZoneId
val jodaLocalDateTime = org.joda.time.LocalDateTime.now()
val javaLocalDateTime = java.time.LocalDateTime.ofInstant(jodaLocalDateTime.toDate.toInstant, ZoneId.systemDefault())