I need to be able to convert data fetched from MySQL database that is stored in a "datetime" fields into Java ZonedDateTime
object.
ZonedDateTime dt = ZonedDateTime.ofInstant(rs.getTimestamp("Start").toInstant(), UTC_ZONE_ID)
The problem I'm having is that toInstant()
adds local time offset to the Timestamp
object which I don't need because the datetime is already stored in a UTC format in a database.
So when I run the following code:
ZonedDateTime startDT =
ZonedDateTime.ofInstant(rs.getTimestamp("Start").toInstant(),Globals.LOCALZONEID);
System.out.println(rs.getTimestamp("start"));
System.out.println(rs.getTimestamp("start").toInstant());
I get:
2017-06-08 13:15:00.0
2017-06-08T17:15:00Z
I need the time component to stay unchanged.
I was unable to find any obvious solution to the problem so am I missing something here?
I think this code snippet answers your question. This takes in a String in a local time zone, converts it to UTC, and stores it in a db.
//Getting the LocalDateTime Objects from String values
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd kk:mm");
String txtStartTime = "2017-03-29 12:00";
LocalDateTime ldtStart = LocalDateTime.parse(txtStartTime, df);
//Convert to a ZonedDate Time in UTC
ZoneId zid = ZoneId.systemDefault();
ZonedDateTime zdtStart = ldtStart.atZone(zid);
System.out.println("Local Time: " + zdtStart);
ZonedDateTime utcStart = zdtStart.withZoneSameInstant(ZoneId.of("UTC"));
System.out.println("Zoned time: " + utcStart);
ldtStart = utcStart.toLocalDateTime();
System.out.println("Zoned time with zone stripped:" + ldtStart);
//Create Timestamp values from Instants to update database
Timestamp startsqlts = Timestamp.valueOf(ldtStart); //this value can be inserted into database
System.out.println("Timestamp to be inserted: " +startsqlts);
//insertDB(startsqlts);