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

Time:10-17

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

CodePudding user response:

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

CodePudding user response:

`   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));'

CodePudding user response:

LocalDateTime dt = LocalDateTime.of(2022,Month.OCTOBER,14,9,0);
System.out.println(dt.format(DateTimeFormatter.ISO_DATE_TIME));

ISO is a standard for dates. Please use new classes (java.time.format.DateTimeFormatter; java.time) Or is it really neccessary to use as input the String variable?

  • Related