Hi I have a table from which I get a date like "2017-03-24 06:01:33" which is in UTC. In my java program I have to receive it as a string. How to convert it to a local date string using client's offset hour and minute?
I would do:
OffsetDateTime odt = LocalDateTime.parse(dateFromDb, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
.atOffset(ZoneOffset.UTC);
String localDateString = odt.atZoneSameInstant(ZoneOffset.ofHoursMinutes(5, 30))
.toLocalDateTime()
.toString();
I am assuming you have got the client’s time zone as an offset in hours and minutes. Then you can pass those into from ZoneOffset.ofHoursMinutes()
. Beware that if the client time zone uses summer time (daylight savings time) some of the year (as is the case in greater parts of the USA), you need to be sure you get the offset for the time of year where the date falls. Other ways of specifying the client time zone would be ZoneId.systemDefault()
or ZoneId.of("Asia/Kolkata")
— such would know the summer time rules and hence may be safer.
The code prints:
2017-03-24T11:31:33
You notice it’s five and a half hours ahead of the input string as expected.
If you only require the date, not the time, use toLocalDate()
instead of toLocalDateTime()
.
All of the above requires Java 8. Or the backport of the Java 8 date and time classes to Java 6 and 7, see ThreeTen Backport. If you cannot use Java 8 and do not want to depend on the backport, find your inspiration in this question: Not able to parse UTC date time to EST local time.