1

Can somebody find what is wrong with this code. I am trying to convert the Date Time value to Long using the Date and Time Stamp.These two always returns two different values for the same date time.

    String date = "2016-01-08 06:23:13.0";
    if(date.lastIndexOf('.') != -1)
    {
        date = date.substring(0,date.lastIndexOf('.'));
        date = date+"+0000";
    }
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
    Date myDate = fmt.parse(date);

    System.out.println(myDate); 
    long timestamp = myDate.getTime();
    System.out.println("The time stamp value is " + timestamp);

    Timestamp tm = Timestamp.valueOf("2016-01-08 06:23:13.0");
    System.out.println("The time stamp value using Timestamp is " + tm.getTime());
Sankar
  • 369
  • 4
  • 17
  • What happens if you do `tm = Timestamp.valueOf(date)`? Those manipulations in lines 2-5 are not being represented in the Timestamp processing. – Mark Larter Jan 08 '16 at 06:45
  • Simply using `SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");` works just fine for me – MadProgrammer Jan 08 '16 at 06:49
  • The first value is been set to +0 time zone, the second is using the current time offset (in my case 9 hours) – MadProgrammer Jan 08 '16 at 06:51

2 Answers2

0

You are adding a time zone specification to your first variant:

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
                                                                ^

If you ommitt this, and specify the same input values for both calculations, the result is the same.

...
    String date = "2016-01-08 06:23:13";

    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date myDate = fmt.parse(date);
    System.out.println(myDate);

    long timestamp = myDate.getTime();
    System.out.println("The time stamp value is " + timestamp);

    Timestamp tm = Timestamp.valueOf(date);
    long t2 = tm.getTime();

    System.out.println("The time stamp value using Timestamp is " + t2 + " (diff: " + (t2 - timestamp) + ")");
...
Fri Jan 08 06:23:13 CET 2016
The time stamp value is 1452230593000
The time stamp value using Timestamp is 1452230593000 (diff: 0)

See @Joni's answer for an explaination:

  • With your explicit timezone specification of +0000 you specify UTC+0 as the time zone
  • Timestamp, on the other hand, assumes your local time zone which leads to a different value unless you live in UTC+0. (Actually it seems a bit more subtle: see Is java.sql.Timestamp timezone specific? for more information)
Community
  • 1
  • 1
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
0

Your code with SimpleDateFormat parses the date assuming the zero digits specify the UTC timezone. Timestamp assumes local timezone.

Joni
  • 108,737
  • 14
  • 143
  • 193