4

Doing the following:

val zonedFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z")

ZonedDateTime.from(zonedFormatter.parse("31.07.2020 14:15 GMT"))

Gives me:

"displayDate": "2020-07-31T14:15:00Z[GMT]"

I want it without the [GMT]:

"displayDate": "2020-07-31T14:15:00Z"
Spectric
  • 30,714
  • 6
  • 20
  • 43
Ry2254
  • 859
  • 1
  • 10
  • 19

1 Answers1

7

You can use DateTimeFormatter.ISO_OFFSET_DATE_TIME to format the parsed ZonedDateTime. However, if you are expecting the date-time always in UTC, I recommend you convert the parsed ZonedDateTime into Instant.

Demo:

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm z", Locale.ENGLISH);

        ZonedDateTime zdt = ZonedDateTime.from(dtfInput.parse("31.07.2020 14:15 GMT"));
        System.out.println(zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));

        System.out.println(zdt.toInstant());
    }
}

Output:

2020-07-31T14:15:00Z
2020-07-31T14:15:00Z

ONLINE DEMO

Learn more about the modern Date-Time API* from Trail: Date Time. Check this answer and this answer to learn how to use java.time API with JDBC.


* 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. Note that Android 8.0 Oreo already provides support for java.time.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110