2

使用 Groovy(或 Java)如何将 a 转换org.joda.time.LocalDateTime为 a 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)

usinglocalDateTime.toDateTime().toDate()给了我java.util.Date6 小时的休息时间我在中部标准时间 (GMT +6)

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

4

2 回答 2

4

在转换期间的某个地方,使用了错误的时区。通过查看默认时区TimeZone.getDefault()和 Joda-Time 默认值来进行调试DateTimeZone.getDefault()

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

localDateTime.toDateTime(yourDesiredZone).toDate()

于 2010-01-06T09:59:47.153 回答
1

编辑:

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

要么使用:

cal.set(Calendar.HOUR_OF_DAY, 0)

或者:

cal.set(Calendar.AM_PM, Calendar.AM)
cal.set(Calendar.HOUR, 0)
于 2010-01-06T04:00:03.280 回答