使用Groovy(或Java)如何将org.joda.time.LocalDateTime转换为java.util.date?

时间:2010-01-05 22:59:13

标签: java datetime groovy jodatime

使用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)的6个小时

如何将LocalDateTime日期转换回java.util.Date以使时间匹配?

2 个答案:

答案 0 :(得分:4)

在转换过程中的某个地方,正在使用错误的时区。通过查看默认时区TimeZone.getDefault()以及Joda-Time默认值DateTimeZone.getDefault()来调试此内容。

您在进行转换时也可以更明确:

localDateTime.toDateTime(yourDesiredZone).toDate()

答案 1 :(得分:1)

编辑:

问题是使用Calendar.HOUR表示上午或下午的小时。

使用:

cal.set(Calendar.HOUR_OF_DAY, 0)

或:

cal.set(Calendar.AM_PM, Calendar.AM)
cal.set(Calendar.HOUR, 0)