将不存在的日期插入内存数据库

时间:2015-07-08 16:25:48

标签: java database date timezone jodatime

我正在尝试将日期 2015-03-08 02:00:00 插入我的Java内存数据库。

日期时间 2015-03-08 02:00:00 在现实生活中并不存在,因为夏令时会在那个确切的时刻发生[至少在美国],意为凌晨2:00 凌晨3:00 。有没有办法忽略这个事实,并将 2015-03-08 02:00:00 直接存储到我的数据库中?

目前我正在使用Java的Date类,但如果找到解决方案,我不反对使用Joda Time。

在Java的日期课程中......

    Date d = new Date();        

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    String date = "2015-03-08 02:00:00.0";

    try 
    {
        d = sdf.parse(date);
        sdf.format(d);
        System.out.println(d);

    } 
    catch (ParseException e) 
    {
        e.printStackTrace();
    }

结果

Sat Mar 07 20:00:00 CST 2015

现在在Joda时间......

    String date = "2015-03-08 02:00:00.0";
    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.S");
    DateTime dt = dtf.parseDateTime(date);

    System.out.println(dt);

结果

Exception in thread "main" org.joda.time.IllegalInstantException: Cannot parse "2015-03-08 02:00:00.0": Illegal instant due to time zone offset transition (America/Chicago)
at org.joda.time.format.DateTimeParserBucket.computeMillis(DateTimeParserBucket.java:471)
at org.joda.time.format.DateTimeParserBucket.computeMillis(DateTimeParserBucket.java:411)
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:882)
at Driver.main(Driver.java:44)

1 个答案:

答案 0 :(得分:0)

存储日期时,将它们存储为长毫秒Utc的优势。 你可以通过date.getTimestamp()获得它; 那你就不用处理时区了。

只有在向用户显示时间时,您应该在显示之前将其转换为当地时间。