开发者

Using Groovy(or Java) how can I convert a org.joda.time.LocalDateTime to a java.util.date?

Using Gr开发者_开发技巧oovy (or Java) how can I convert a org.joda.time.LocalDateTime to 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)

using localDateTime.toDateTime().toDate() gives me a java.util.Date that is 6 hours off I'm in Central Standard time (GMT +6)

How do I convert my LocalDateTime date back to a java.util.Date such that the time matches?


Somewhere during the conversion, the wrong time zone is being used. Debug this by seeing what the default time zone is TimeZone.getDefault() and what the Joda-Time default is DateTimeZone.getDefault().

You can be more explicit when doing the conversion too:

localDateTime.toDateTime(yourDesiredZone).toDate()


EDIT:

The problem is the use of Calendar.HOUR which indicates the hour of the morning or afternoon.

Either use:

cal.set(Calendar.HOUR_OF_DAY, 0)

or:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜