Vik
Vik

Reputation: 9319

converting date timezone format in java

Wrote below code for trying to convert date time from the value in double quotes but fails with parse exception. please advise

public static void main(String args[]) {
    try {

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S Z");
        Date date = format.parse("2016-02-03 10:39:29.099545 -8:00");
    } catch (ParseException pe) {
        // TODO: Add catch code
        pe.printStackTrace();
    }
}

this fails with parse exception.

further more my final output should look like below format: 2016-01-26T12:07:41-08:00

Upvotes: 0

Views: 1778

Answers (2)

Carlos Romero
Carlos Romero

Reputation: 31

The representation of the time zone doesn't correspond with the string "-8:00". You can use three types of time zone representation:

  1. X (ISO 8601 time zone):
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S XXX");
Date date = format.parse("2016-02-03 10:39:29.099545 -08:00");
  1. Z (RFC 822 time zone):
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S Z");
Date date = format.parse("2016-02-03 10:39:29.099545 -0800");
  1. z (General):
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S zzz");
Date date = format.parse("2016-02-03 10:39:29.099545 GMT-08:00");

Check SimpleDateFormat documentation

To convert from Date to the String you desire use this format:

DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
String str = format2.format(date);

But for ISO 8601 Time zone standard, consider this from SimpleDateFormat documentation:

For formatting, if the offset value from GMT is 0, "Z" is produced

Check SimpleDateFormat ignores “XXX” if timezone is set to “UTC”

Upvotes: 3

SubOptimal
SubOptimal

Reputation: 22993

To format a date into ISO 8601 you could use below snippet.

// pre Java 8
TimeZone timeZone = TimeZone.getTimeZone("PST");
GregorianCalendar cal = new GregorianCalendar(timeZone);
cal.set(2016, 1, 26, 12, 7, 41);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
sdf.setTimeZone(timeZone);
System.out.println(sdf.format(cal.getTime())); 

The formatting rules of SimpleDateFormat.

// Java 8
LocalDateTime dateTime = LocalDateTime.of(2016, 1, 26, 12, 7, 41);
ZonedDateTime of = ZonedDateTime.of(dateTime, ZoneId.of("-0800"));
DateTimeFormatter pattern = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
String format = pattern.format(of);
System.out.println(format);

Javadoc of DateTimeFormatter.


output of both snippets

2016-02-26T12:07:41-0800

Upvotes: 2

Related Questions