fatherazrael
fatherazrael

Reputation: 5987

Java Timezone Formatting incorrectly (yyyy-MM-dd'T'HH:mm:ssZ)

Timezone is not correctly formatted

    String fromDate = "2022-10-14T10:00:00+0300";
    final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    Date date = dateFormat.parse(fromDate);   
    System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(date));

When run i am getting my local zone

2022-10-14T12:30:00+0430

Upvotes: 1

Views: 90

Answers (2)

Chaosfire
Chaosfire

Reputation: 7005

Java Date has no concept of time zone and offset, it is actually an instant since the epoch and when you toString() it, it silently uses the default time zone for formatting. You already have an answer regarding the legacy API, so i'll post one about java.time, the modern date-time API, available since java 8.

Parsing and formatting date/time is done with DateTimeFormatter. The input string contains only offset, without timezone, in order to retain this information you need to parse it to OffsetDateTime.

String fromDate = "2022-10-14T10:00:00+0300";
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
OffsetDateTime dateTime = OffsetDateTime.parse(fromDate, parseFormatter);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
System.out.println(outputFormatter.format(dateTime));
//prints - 2022-10-14T10:00:00.000+0300

Upvotes: 1

Deebika Karuppusamy
Deebika Karuppusamy

Reputation: 16

`   String fromDate = "2022-10-14T10:00:00+0300";
    final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
       
    Date date = dateFormat.parse(fromDate);   
    dateFormat.setTimeZone(TimeZone.getTimeZone("EAT"));
    System.out.println(dateFormat.format(date));'

Upvotes: 0

Related Questions