-1

I am trying to insert the date 2015-03-08 02:00:00 into my Java in-memory database.

The DateTime 2015-03-08 02:00:00 doesn't exist in real life, because daylights savings time occurs at that exact moment [at least in the USA], meaning 2:00 AM becomes 3:00 AM. Is there any way to ignore this fact, and store 2015-03-08 02:00:00 straight into my database?

Currently I am using Java's Date class, but I am not opposed to using Joda Time if it will find a solution.

In Java's Date class...

    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();
    }

results in

Sat Mar 07 20:00:00 CST 2015

Now in Joda Time...

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

results in

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)
Joshua
  • 7
  • 6
  • 1
    Can you please share your code and your error message? – Mureinik Jul 08 '15 at 16:29
  • @Mureinik If I use Java's Date library, I'm not getting any errors. Whenever I create and instantiate a new Date with **2015-03-08 02:00:00**, it automatically changes to **2015-03-08 03:00:00**. – Joshua Jul 08 '15 at 16:48
  • possible duplicate of [Storing a "fake" timestamp into a database](http://stackoverflow.com/questions/31279064/storing-a-fake-timestamp-into-a-database). Please do not spam StackOverflow by posting repeatedly. Edit your original question if you have clarifications or additional information. – Basil Bourque Jul 08 '15 at 19:49

1 Answers1

0

When storing dates, its an advantage to store them as long milliseconds Utc. You get that by date.getTimestamp(); Then you dont have to deal with time zones.

Only when displaying a time to the user you should convert it to local time, immedeatly before you display it.

AlexWien
  • 28,470
  • 6
  • 53
  • 83