繁体   English   中英

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

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

使用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 ,比我在中部标准时间(GMT +6)少6个小时

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

转换过程中的某个位置使用了错误的时区。 通过查看默认时区为TimeZone.getDefault()以及Joda-Time默认为DateTimeZone.getDefault()调试。

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

localDateTime.toDateTime(yourDesiredZone).toDate()

编辑:

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

可以使用:

cal.set(Calendar.HOUR_OF_DAY, 0)

要么:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM