Search code examples
javadatesimpledateformatformatter

SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); customize the timezone


I want to print the date with the char ":" in the middle of timezone, example :

2023-08-02T14:19:10+02:00

At the moment I am using this pattern:

SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

and it prints:

2023-08-02T14:19:10+0200

Any idea?

below an example of code :

public class testDate {

    public static final DateFormat PATTERN = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

    public static String calendarToString(final Calendar dateToConvert, final DateFormat df) {
        return df.format(dateToConvert.getTime());
    }

    public static void main(String[] args) {
        Calendar effectiveDate = Calendar.getInstance();
        System.out.println(calendarToString(effectiveDate, PATTERN));
    }
}

Solution

  • You need to use XXX instead of Z to get a timezone formatted as {Z|{+|-}HH:mm}. That said, you should really switch to using the new java.time types, and stop using SimpleDateFormat.

    This is shown in one of the examples in the SimpleDateFormat documentation:

    Date and Time Pattern Result
    ... ...
    "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00