-2

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

1 Answers1

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)

ONLINE DEMO

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