Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Alphabetic Characters in SimpleDateFormat Pattern String

Is it possible to include an alphabetic character in a SimpleDateFormat Pattern String?

I am trying to create a format string where the letter 'T' is included before the time for example:

2003-11-15T09:30:47-05:00.

I am currently using yyyy-MM-ddhh:mm:ssZ as the pattern string.

If I change it to yyyy-MM-ddThh:mm:ssZ it will throw an exception as 'A' to 'Z' and 'a' to 'z' are reserved.

Is there any solution that does not involve using two DateFormats?

like image 953
Gordon Avatar asked Mar 10 '10 12:03

Gordon


People also ask

Is SimpleDateFormat deprecated?

Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

Is SimpleDateFormat case sensitive?

The formats are case-sensitive. Use yyyy for year, dd for day of month and MM for month. You need to read the javadoc of SimpleDateFormat more carefully, Take special care for lower-case and upper-case in the patterns.

Is SimpleDateFormat a String?

SimpleDateFormat also supports localized date and time pattern strings. In these strings, the pattern letters described above may be replaced with other, locale dependent, pattern letters. SimpleDateFormat does not deal with the localization of text other than the pattern letters; that's up to the client of the class.


1 Answers

Surrounding the T with single quotes should work:

yyyy-MM-dd'T'hh:mm:ssZ 

Quoting from the documentation (emphasis mine):

Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

Your specific use case is even included as an example:

Date and Time Pattern            Result ------------------------------------------------------------- "yyyy-MM-dd'T'HH:mm:ss.SSSZ"     2001-07-04T12:08:56.235-0700   
like image 92
Joey Avatar answered Oct 12 '22 05:10

Joey