I am trying to convert from java.sql.timestamp
to OffsetDateTime
so that i can return ISO8601
standard string in my rest api. I am using this code to convert from timestamp
to OffsetDateTime
public static OffsetDateTime sqlTimetampeToOffsetDateTime(Timestamp ts, String timeZone)
{
if (ts == null)
{
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(ts);
ZoneOffset offset = ZoneOffset.of(timeZone);
return OffsetDateTime.of(
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH)+1,
cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE),
cal.get(Calendar.SECOND),
cal.get(Calendar.MILLISECOND)*1000000,
offset);
}
However, the code fails at ZoneOffset offset = ZoneOffset.of(timezone)
for value Europe/Copenhagen
.
I used following code to print list of all timezones and i do see Europe/Copenhagen
in that list
Set<String> allZones = ZoneId.getAvailableZoneIds();
LocalDateTime dt = LocalDateTime.now();
List<String> zoneList = new ArrayList<String>(allZones);
Collections.sort(zoneList);
for (String s : zoneList) {
ZoneId zone = ZoneId.of(s);
ZonedDateTime zdt = dt.atZone(zone);
ZoneOffset offset = zdt.getOffset();
int secondsOfHour = offset.getTotalSeconds() % (60 * 60);
String out = String.format("%35s %10s%n", zone, offset);
System.out.printf(out);
}
Now I don't understand what is going on. How can i convert java.sql.timestamp
to ISO8601
string (i don't care if i have to use OffsetDateTime
or not. I would prefer not to use any third party library