Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Extend SimpleDateFormat with new pattern letters

Java's SimpleDateFormat is used to format a Date object to a string. The formatter supports various pattern letters, which denote textual representation of a Date field. For example, yy is two-letter year, yyyy is four-letter year, and E is day of week.

For example, A SimpleDateFormat initialized with yyyy.MM.dd G 'at' HH:mm:ss z will format a date to something like 2001.07.04 AD at 12:08:56 PDT.

I would like to add some pattern letters to SimpleDateFormat. For example, want C to denote Hebrew weekday (יום ראשון, יום שני, ...).

What's the right way to extend SimpleDateFormat with these new pattern letters? The only online example I could find seems somewhat complicated. I can live with formatting only, without parsing.

like image 575
Adam Matan Avatar asked Sep 03 '25 05:09

Adam Matan


2 Answers

E can already be used to get the day of the week. If you want it in hebrew, then initialize the SimpleDateFormat instance with the hebrew locale.

like image 61
JB Nizet Avatar answered Sep 04 '25 19:09

JB Nizet


From what I can tell SDF was not build to be extendable so each Calendar field formatting is hardcoded into one method : (. What I would do is I would create a wrapper object and detect special (handled by me chars) and format output by my own in mixed formats i would divide format into whats before and after my format char, and pass them to original SDF and then glue the results together.

like image 26
damiankolasa Avatar answered Sep 04 '25 18:09

damiankolasa