如何处理jodatime由于时区偏移过渡而导致的非法瞬发 [英] How to handle jodatime Illegal instant due to time zone offset transition

查看:107
本文介绍了如何处理jodatime由于时区偏移过渡而导致的非法瞬发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将joda DateTime 设置为今天凌晨2点(请参阅下面的示例代码)。但是我得到了这个例外:

I want to set up joda DateTime to today at 2 AM (see sample code below). But I'm getting this exception:

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 是什么?

What is the correct way to the handle exception above or to create a DateTime at a particular hour of day?

示例代码:

MutableDateTime now = new MutableDateTime();
now.setHourOfDay(2);
now.setMinuteOfHour(0);
now.setSecondOfMinute(0);
now.setMillisOfSecond(0);
DateTime myDate = now.toDateTime();

谢谢。

推荐答案

看起来你正试图从特定的本地时间到 DateTime 实例,并且你希望它能够对夏令时产生强大的影响。试试这个......(注意我在美国/东部,所以我们的过渡日期是3月13日;我必须找到正确的日期来获得你今天得到的例外。更新我的CET代码,今天转换。这里的见解是Joda提供 LocalDateTime 让您了解当地的挂钟设置,以及它是否在您的时区合法。在这种情况下,如果时间不存在,我只需添加一小时(您的应用程序必须确定这是否是正确的策略。)

It seems like you're trying to get from a specific local time to a DateTime instance and you want that to be robust against daylight savings. Try this... (note I'm in US/Eastern, so our transition date was 13 Mar 11; I had to find the right date to get the exception you got today. Updated my code below for CET, which transitions today.) The insight here is that Joda provides LocalDateTime to let you reason about a local wall-clock setting and whether it's legal in your timezone or not. In this case, I just add an hour if the time doesn't exist (your application has to decide if this is the right policy.)

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

这篇关于如何处理jodatime由于时区偏移过渡而导致的非法瞬发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆