Question

Is there an equivalent to php date() style formatting in Java? I mean, in php I can backslash-escape characters to have them treated literally. I.e. yyyy \y\e\a\r would become 2010 year. I did not find anything similar in Java, all examples deal only with built-in date formats.

In particular, I deal with JCalendar date pickers and their dateFormatString property.

I need it because in my locale it is required to write all sorts of additional stuff in date format, like d. (for day) after days part, m. (for years) after years part and so on. At the worst case I could use string replace or regexp but maybe there's a simpler way? Thanks in advance!

Was it helpful?

Solution

Sure, with the SimpleDateFormat you can include literal 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.

 "hh 'o''clock' a, zzzz"    12 o'clock PM, Pacific Daylight Time

OTHER TIPS

Just for completeness, Java 8's DateTimeFormatter also supports this:

DateTimeFormatter.ofPattern("yyyy 'year'");

You can use String.format as documented in java.util.Formatter:

Calendar c = ...;
String s = String.format("%tY year", c);
// -> s == "2010 year" or whatever the year actually is

java.text.SimpleDateFormat

SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); 
String formattedDate = formatter.format(date);

You'll get more info here link text

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top