Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use java.time.ZonedDateTime & format.DateTimeFormatter without GMT?

Tags:

java

java-time

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"
like image 426
fullStackRyan Avatar asked Mar 01 '23 10:03

fullStackRyan


1 Answers

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.

like image 198
Arvind Kumar Avinash Avatar answered Apr 26 '23 19:04

Arvind Kumar Avinash