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

ε祈祈猫儿з 提交于 2020-02-02 11:12:33

问题


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:


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)



回答2:


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



来源:https://stackoverflow.com/questions/2009795/using-groovyor-java-how-can-i-convert-a-org-joda-time-localdatetime-to-a-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!