views:

797

answers:

2

Using Groovy (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?

+1  A: 

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)
Chandra Patni
I wasn't clear with my example, I have updated what I meant as well as used equals() for the sake of clarity. (Groovy handles date equality using '==' [which utilizes equals()] and 'is' for identity)
Colin Harrington
?? I think Chandra is right, as your example exists now the "startOfTheMonth" = "Fri Jan 01 12:00:00 CST 2010" and dateFromLocalDate is "Fri Jan 01 00:00:00 CST 2010", they're off by 12 hours, not 6 hours that you'd get for CST offset from GMT. If you switch to HOUR_OF_DAY instead of HOUR, the assertion works.
Ted Naleid
I'm getting different results: startOfTheMonth = "Jan 01 12:00:00 CST 2010" and dateFromLocalDate = "dateFromLocalDate" Does the Example assertion work for you?
Colin Harrington
A: 

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()

JodaStephen