How to get just some time zone that matches the offset using java.time
I tend to understand from your comment under Arvind Kumar Avinash’ answer that you have solved it by simply taking the first time zone that has the correct offset (or what you thought was the correct offset). Of course java.time, the modern Java date and time API, can do that. I wanted to show you a way.
String input = "2021-09-29T17:04:31.0000 +05:30";
// Remove space and parse
OffsetDateTime dateTime = OffsetDateTime.parse(input.replace(" ", ""));
ZoneOffset offset = dateTime.getOffset();
// Find and convert to a zone that matches the offset (there will usually be many)
ZonedDateTime zonedDateTime = ZoneId.getAvailableZoneIds()
.stream()
.map(ZoneId::of)
.map(dateTime::atZoneSameInstant)
.filter(zdt -> zdt.getOffset().equals(offset))
.findFirst()
// If all else fails, use the offset as time zone
.orElse(dateTime.atZoneSameInstant(offset));
// Convert to 2021-09-29 17:04:31.0000000 Asia/Calcutta format
String result = zonedDateTime.format(FORMATTER);
System.out.println(result);
I have used this formatter for formatting the output:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSS VV", Locale.ROOT);
And the output is (on my Java 11):
2021-09-29 17:04:31.000000 Asia/Kolkata
Asia/Kolkata is the present-day name for the time zone formerly known as Asia/Calcutta. Is that close enough?
In my code I have taken the case into account where no suitable time zone exists. Let’s see this with an offset that I don’t think is used in any real time zone:
String input = "2021-10-06T18:54:31.0000 +00:30";
2021-10-06 18:54:31.000000 +00:30
If you didn’t want this, you will at least need to change the line with the call to orElse()
.