使用Groovy(或Java)如何将org.joda.time.LocalDateTime转换为java.util.date?
使用Groovy(或Java)如何将org.joda.time.LocalDateTime
转换为java.util.Date
?
import org.joda.time.* Calendar cal = Calendar.instance cal.set(Calendar.DATE, 1) cal.set(Calendar.HOUR, 0) cal.set(Calendar.MINUTE, 0) cal.set(Calendar.SECOND, 0) cal.set(Calendar.MILLISECOND, 0) Date startOfTheMonth = cal.time LocalDateTime localDateTime = new LocalDateTime() localDateTime = localDateTime.withDayOfMonth(1) localDateTime = localDateTime.withTime(0,0,0,0) localDateTime.minusMonths(6) Date dateFromLocalDate = localDateTime.toDateTime().toDate() println startOfTheMonth println dateFromLocalDate assert startOfTheMonth.equals(dateFromLocalDate)
使用localDateTime.toDateTime().toDate()
给我一个java.util.Date
,这是6小时关闭我在中央标准时间(GMT +6)
如何将我的LocalDateTime
日期转换回java.util.Date
以使时间匹配?
编辑:
问题是使用Calendar.HOUR表示上午或下午的小时。
使用:
cal.set(Calendar.HOUR_OF_DAY, 0)
要么:
cal.set(Calendar.AM_PM, Calendar.AM) cal.set(Calendar.HOUR, 0)
在转换过程中的某个地方,正在使用错误的时区。 通过查看默认时区是TimeZone.getDefault()
以及Joda-Time默认为DateTimeZone.getDefault()
调试此问题。
在进行转换时,您可以更明确:
localDateTime.toDateTime(yourDesiredZone).toDate()