Friday, December 16, 2011

java.lang.IllegalArgumentException: Illegal pattern character 'AT'

I got below mentioned error, while trying to add characters other than pre defined date pattern.

Exception in thread "main" java.lang.IllegalArgumentException: Illegal pattern character 'AT'
    at java.text.SimpleDateFormat.compile(SimpleDateFormat.java:769)
    at java.text.SimpleDateFormat.initialize(SimpleDateFormat.java:576)
    at java.text.SimpleDateFormat.(SimpleDateFormat.java:501)
    at java.text.SimpleDateFormat.(SimpleDateFormat.java:476)

To add your desire Characters or String you need to by-pass it using escape sequence. Please see the correct syntax below. Note the escape character single quote ('), whatever you want to pass a Characters or String need to by-pass it using escape character single quote (').

Correct Syntax:

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdFormat =  new SimpleDateFormat("yyyy-MM-dd 'AT' hh:mm:ss");
String strDate = sdFormat.format(cal.getTime());
System.out.println("Now : "+strDate);

Output:

Now : 2011-12-16 AT 03:57:40