Search code examples
javadatetimesimpledateformat

Unable to format string-date of format `Sun Apr 10 21:26:54 +05:30 2022` in java


In java,

Unable to parse date-Strings of this format Sun Apr 10 21:26:54 +05:30 2022.

I am using java.text.SimpleDateFormat to parse this String.

The pattern that i'm using : E MMM dd hh:mm:ss X yyyy

I'm mainly unable to work if the timezone (+05:30) is present before the year-value.

X seems to work only if it is at the end of the String.

I have tried Z, but it doesn't work.

Sample code :

String dateStr = "Sun Apr 10 21:26:54 +05:30 2022";
java.util.Date epoch = new java.text.SimpleDateFormat("E MMM dd hh:mm:ss X yyyy")
                .parse(dateStr);

Error im getting :

Exception in thread "main" java.text.ParseException: Unparseable date: "Sun Apr 10 21:26:54 +05:30 2022"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at com.company.ExifDataExtractor.main(ExifDataExtractor.java:51)


Solution

  • You need to use "X" 3 times for this format according the docs.

    Offset X and x: This formats the offset based on the number of pattern letters. One letter outputs just the hour, such as '+01', unless the minute is non-zero in which case the minute is also output, such as '+0130'. Two letters outputs the hour and minute, without a colon, such as '+0130'. Three letters outputs the hour and minute, with a colon, such as '+01:30'. Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'. Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'. Six or more letters throws IllegalArgumentException. Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero, whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.

    java.util.Date epoch = new java.text.SimpleDateFormat("E MMM dd hh:mm:ss XXX yyyy").parse(dateStr);