3
votes

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.

3
FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle. - Basil Bourque

3 Answers

4
votes

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.

1
votes

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.

-1
votes

java.time

The modern DateTimeFormatter years ago supplanted SimpleDateFormat, with the adoption of JSR 310.

Study that class JavaDoc to see its many formatting codes. While largely similar to the codes used in the SimpleDateFormat class, there are some differences.

This class can automatically localize for you. So you may not need to define any formatting pattern.

If you want just the name of the day of the week localized, use DayOfWeek::getDisplayName method.