1

I am using a SQL Server which has a column with dateTime. I want to insert the user input String into the DB, for which i try to insert using timestamp.

Following code in Java converts String to ZonedDateTime.

Case 1:

String ip="2018-05-01T06:47:35.422-05:00";
ZonedDateTime zdt = ZonedDateTime.parse(ip, DateTimeFormatter.ISO_ZONED_DATE_TIME);
System.out.println(Timestamp.from(zdt.toInstant()));

Output is 2018-05-01 06:47:35.422

Case 2:

If String ip="2011-04-07T00:00:00.000-04:00"; Output is 2011-04-06 23:00:00.0

In the second case, why is the date getting changed to previous day and the time is considering offset?

Joe Coder
  • 4,498
  • 31
  • 41

1 Answers1

2

Below is the code I tried. Notice that since I am in -7:00 timezone, it subtracts an additional 2 hours from the -5:00 specified in the time string. Since you are not seeing an offset, I presume you are in the -5:00 timezone. That is why in your 2nd case (-4:00 string), it must subtract an additional 1 hour, putting it in the day before.

public static void main(String[] args) {
    String ip="2018-05-01T06:47:35.422-05:00";
    ZonedDateTime zdt = ZonedDateTime.parse(ip, DateTimeFormatter.ISO_ZONED_DATE_TIME);

    // my timezone is: -7:00
    System.out.println(zdt.toInstant());                 // 2018-05-01T11:47:35.422Z
    System.out.println(Timestamp.from(zdt.toInstant())); // 2018-05-01 04:47:35.422
}
Joe Coder
  • 4,498
  • 31
  • 41