我想设置jodaDateTime
到今天凌晨 2 点(请参阅下面的示例代码)。但我遇到了这个异常:
Exception in thread "main" org.joda.time.IllegalFieldValueException: Value 2 for hourOfDay is not supported: Illegal instant due to time zone offset transition: 2011-03-27T02:52:05.239 (Europe/Prague)
at org.joda.time.chrono.ZonedChronology$ZonedDateTimeField.set(ZonedChronology.java:469)
at org.joda.time.MutableDateTime.setHourOfDay(MutableDateTime.java:702)
处理上述异常或创建异常的正确方法是什么DateTime
在一天中的某个特定时间?
示例代码:
MutableDateTime now = new MutableDateTime();
now.setHourOfDay(2);
now.setMinuteOfHour(0);
now.setSecondOfMinute(0);
now.setMillisOfSecond(0);
DateTime myDate = now.toDateTime();
Thanks.
似乎您正在尝试从特定的本地时间到DateTime
例如,您希望它能够抵抗夏令时。试试这个...(注意我在美国/东部,所以我们的过渡日期是 2011 年 3 月 13 日;我必须找到正确的日期才能获得今天的例外情况。更新了下面的 CET 代码,该代码今天过渡。 )这里的见解是 Joda 提供LocalDateTime http://joda-time.sourceforge.net/apidocs/org/joda/time/LocalDateTime.html让您了解当地的挂钟设置以及它在您的时区是否合法。在这种情况下,如果时间不存在,我只需添加一个小时(您的应用程序必须决定这是否是正确的策略。)
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
class TestTz {
public static void main(String[] args)
{
final DateTimeZone dtz = DateTimeZone.forID("CET");
LocalDateTime ldt = new LocalDateTime(dtz)
.withYear(2011)
.withMonthOfYear(3)
.withDayOfMonth(27)
.withHourOfDay(2);
// this is just here to illustrate I'm solving the problem;
// don't need in operational code
try {
DateTime myDateBorken = ldt.toDateTime(dtz);
} catch (IllegalArgumentException iae) {
System.out.println("Sure enough, invalid instant due to time zone offset transition!");
}
if (dtz.isLocalDateTimeGap(ldt)) {
ldt = ldt.withHourOfDay(3);
}
DateTime myDate = ldt.toDateTime(dtz);
System.out.println("No problem: "+myDate);
}
}
该代码产生:
Sure enough, invalid instant due to time zone offset transition!
No problem: 2011-03-27T03:00:00.000+02:00
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)