I need to convert the date from 2021-08-21T17:36:51.000+00:00 to 2021-08-21 06:36 PM BST(+1) using java any help
Asked
Active
Viewed 116 times
-2
-
If the date is not in the summer time (DST) part of the year, which result do you want then? – Ole V.V. Aug 23 '21 at 18:36
-
3Welcome to Stack Overflow. What have you tried so far in order to find an answer? – Yun Aug 23 '21 at 19:55
1 Answers
2
You can use OffsetDateTime#withOffsetSameInstant
to meet this requirement.
Demo:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
OffsetDateTime source = OffsetDateTime.parse("2021-08-21T17:36:51.000+00:00");
OffsetDateTime target = source.withOffsetSameInstant(ZoneOffset.of("+01:00"));
System.out.println(target);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd hh:mm a O", Locale.ENGLISH);
String formatted = dtf.format(target);
System.out.println(formatted);
// Replace GMT with BST to get the required string
formatted = formatted.replaceFirst("GMT([+\\-]\\d+)", "BST($1)");
System.out.println(formatted);
}
}
Output:
2021-08-21T18:36:51+01:00
2021-08-21 06:36 PM GMT+1
2021-08-21 06:36 PM BST(+1)
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
- 71,965
- 6
- 74
- 110
-
I need the output date to be 2021-08-21 06:36 PM BST(+1) not 2021-08-21T18:36:51+01:00 – David Ishak Aug 23 '21 at 18:18
-
@DavidIshak - BST (British Summer Time) is not a standard timezone name. Anyway, I've posted a solution to meet your specific requirement. – Arvind Kumar Avinash Aug 23 '21 at 18:34