SimpleDateFormat throw java.lang.IllegalArgumentException at runtime while parsing date format.
Follow link below to get in depth knowledge of IllegalArgumentException .
[Solved] java.lang.IllegalArgumentException: “ABC”
Example DateTime throwing IllegalArgumentexception
In this example target format is throwing IllegalArgumentException because of using invalid formatting char for display AM/PM.
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class ChangeDateFormat { public static void main(String[] args) { String targetFormat = "MM/DD/YYYY hh:mm:ss AM/PM"; String currentFormat = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'"; String sourceDate = "2019-02-12T11:29:10.761Z"; System.out.println("Source Date :"+sourceDate); String timezone = "CDT"; DateFormat srcDf = new SimpleDateFormat(currentFormat); srcDf.setTimeZone(TimeZone.getTimeZone(timezone)); DateFormat destDf = new SimpleDateFormat(targetFormat); try { Date date = srcDf.parse(sourceDate); String targetDate = destDf.format(date); System.out.println("Target Date :"+targetDate); } catch (ParseException ex) { ex.printStackTrace(); } } }
Output:
Source Date :2019-02-12T11:29:10.761Z
Exception in thread "main" java.lang.IllegalArgumentException: Illegal pattern character 'A'
at java.text.SimpleDateFormat.compile(Unknown Source)
at java.text.SimpleDateFormat.initialize(Unknown Source)
at java.text.SimpleDateFormat.(Unknown Source)
at java.text.SimpleDateFormat.(Unknown Source)
at com.fiot.test.ChangeDateFormat.main(ChangeDateFormat.java:19)
Solutions :
SimpleDateFormat allow only some key characters only while using date time formatting. Here for showing AM/PM should use character as a as mentioned in below code in targetFormat. Follow link to see complete list for formatting characters and date format.
Date Time Formatting Characters and Patterns
Correct format to AM/PM
"MM/DD/YYYY hh:mm:ss a"
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class ChangeDateFormat { public static void main(String[] args) { String targetFormat = "MM/DD/YYYY hh:mm:ss a"; String currentFormat = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'"; String sourceDate = "2019-02-12T11:29:10.761Z"; System.out.println("Source Date :"+sourceDate); String timezone = "CDT"; DateFormat srcDf = new SimpleDateFormat(currentFormat); srcDf.setTimeZone(TimeZone.getTimeZone(timezone)); DateFormat destDf = new SimpleDateFormat(targetFormat); try { Date date = srcDf.parse(sourceDate); String targetDate = destDf.format(date); System.out.println("Target Date :"+targetDate); } catch (ParseException ex) { ex.printStackTrace(); } } }
Output:
Source Date :2019-02-12T11:29:10.761Z
Target Date :02/43/2019 04:59:10 PM
More Issues Solution
To solved Date Time same code , formatting and issues solutions follow the link given below:
You must log in to post a comment.