简体   繁体   中英

Joda LocalDateTime IllegalFieldValueException when converting to java.util.Date

提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供   中文简体   中文繁体   中英对照 版本,有任何建议请联系yoyou2525@163.com。

I'm using JodaTime for the first time and don't understand what is wrong with this:

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

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?

2 anwsers

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

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.

  LocalDateTime localDateTime = new LocalDateTime(1965, 4, 8, 15, 16, 17, 18);
  Date date = localDateTime.toDateTime().toDate();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question
 
粤ICP备18138465号  © 2020-2022 STACKOOM.COM