[英]Joda LocalDateTime IllegalFieldValueException when converting to java.util.Date
I'm using JodaTime for the first time and don't understand what is wrong with this: 我第一次使用JodaTime并且不明白这有什么问题:
LocalDateTime localDateTime = new LocalDateTime(1965, 4, 8, 15, 16, 17, 18);
Date date = localDateTime.toDate();
when I run this I get: 当我运行这个时,我得到:
org.joda.time.IllegalFieldValueException: Value -982 for millisOfSecond must be in the range [0,999]
but if I do this (no millis), I don't get the exception: 但如果我这样做(没有毫米),我不会得到例外:
LocalDateTime localDateTime = new LocalDateTime(1965, 4, 8, 15, 16, 17);
Date date = localDateTime.toDate();
And I don't get the exception with (ie year = 1975): 我没有得到例外(即年= 1975年):
LocalDateTime localDateTime = new LocalDateTime(1975, 4, 8, 15, 16, 17, 18);
Date date = localDateTime.toDate();
What's going on? 这是怎么回事? Are there some restrictions about converting to java.util.Date?
转换为java.util.Date有一些限制吗?
The following is usually right. 以下通常是正确的。 But not this time.
但不是这次。
Always use
.getMillis()
in Joda - it will give you millisecond time range from Epoch and allow flawless (Java API)
Date()
construction - like this:
new Date(millis)
.
始终在Joda中使用
.getMillis()
- 它将为您提供Epoch的毫秒时间范围,并允许完美无缺的(Java API)
Date()
构造 - 如下所示:
new Date(millis)
。
So, summing up:
所以,总结一下:
LocalDateTime localDateTime = new LocalDateTime(1975, 4, 8, 15, 16, 17, 18); Date date = new Date(localDateTime.getLocalMillis());
This is the solution that actually works: 这是实际工作的解决方案:
LocalDateTime ldt = new LocalDateTime( 1975, 4, 8, 15, 16, 17, 18 ); DateTime dt = new DateTime( ldt.getYear(), ldt.getMonthOfYear(), ldt.getDayOfMonth(), ldt.getHourOfDay(), ldt.getMinuteOfHour(), ldt.getSecondOfMinute(), ldt.getMillisOfSecond()); Date d = new Date( dt.getMillis() );
And 1965 is before Epoch... i don't know how it affects Date and millis, but, yeah, just saying. 并且1965年在Epoch之前...我不知道它如何影响Date和millis,但是,是的,只是说。
LocalDateTime localDateTime = new LocalDateTime(1965, 4, 8, 15, 16, 17, 18);
Date date = localDateTime.toDateTime().toDate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.