java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API.
Solution using java.time API
Parse the given time string using LocalTime#parse
and then convert it into a UTC OffsetTime
by using LocalTime#atOffset
. The final step is to convert this UTC OffsetTime
into an OffsetTime
at the offset of +03:00
which you can do by using OffsetTime#withOffsetSameInstant
.
Note that you do not need a DateTimeFormatter
to parse your time string as it is already in ISO 8601 format, which is the default format that is used by java.time
types.
Demo:
class Main {
public static void main(String args[]) {
String sampleTime = "12:30";
OffsetTime offsetTime = LocalTime.parse(sampleTime)
.atOffset(ZoneOffset.UTC)
.withOffsetSameInstant(ZoneOffset.of("+03:00"));
System.out.println(offsetTime);
// Gettting LocalTine from OffsetTime
LocalTime result = offsetTime.toLocalTime();
System.out.println(result);
}
}
Output:
15:30+03:00
15:30
Online Demo
Alternatively,
class Main {
public static void main(String args[]) {
String sampleTime = "12:30";
OffsetTime offsetTime = OffsetTime.of(LocalTime.parse(sampleTime), ZoneOffset.UTC)
.withOffsetSameInstant(ZoneOffset.of("+03:00"));
System.out.println(offsetTime);
// Gettting LocalTine from OffsetTime
LocalTime result = offsetTime.toLocalTime();
System.out.println(result);
}
}
Online Demo
Learn more about the modern Date-Time API from Trail: Date Time.