Java date format - including additional characters
Asked Answered
T

5

118

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?

Thirtyone answered 26/1, 2010 at 7:50 Comment(1)
For anyone reading this in 2019 or later, the SimpleDateFormat class used in a couple of the answers is notoriously troublesome and long outdated. Avoid it. Instead use the short answer by Mark Jeronimus demonstrating the use of java.time, the modern Java date and time API.Jumbo
H
198

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
Haler answered 26/1, 2010 at 8:5 Comment(5)
Super, thats exactly what I need. Surprisingly I haven't found such simple thing in any of numerous examples I browsed in web :) Thanks a lot!Thirtyone
How do I escape quote character? I'm trying to do something with the format mm'. Indicating for example 46 minutes like 46'.Pterous
@Sotti: 46''. The first to escape the second.Haler
FYI, the terribly troublesome 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.Adermin
This is the what I was exactly looking for, Thanks!Notional
C
40

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

DateTimeFormatter.ofPattern("yyyy 'year'");
Colincolinson answered 5/4, 2018 at 8:29 Comment(0)
J
11

java.time

Mark Jeronimus said it already. I am fleshing it out a bit more. Just put the text to be printed literally inside single quotes.

    DateTimeFormatter yearFormatter = DateTimeFormatter.ofPattern("yyyy 'year'");
    System.out.println(LocalDate.of(2010, Month.FEBRUARY, 3).format(yearFormatter));
    System.out.println(Year.of(2010).format(yearFormatter));
    System.out.println(ZonedDateTime.now(ZoneId.of("Europe/Vilnius")).format(yearFormatter));

Output when running just now:

2010 year
2010 year
2019 year

If you are using a DateTimeFormatterBuilder and its appendPattern method, use single quotes in the same way. Or use its appendLiteral method instead and no single quotes.

How do we put a single quote in the format, then? Two single quotes produce one. It doesn’t matter if the double single quote is inside single quotes or not:

    DateTimeFormatter formatterWithSingleQuote = DateTimeFormatter.ofPattern("H mm'' ss\"");
    System.out.println(LocalTime.now(ZoneId.of("Europe/London")).format(formatterWithSingleQuote));

10 28' 34"

    DateTimeFormatter formatterWithSingleQuoteInsideSingleQuotes
            = DateTimeFormatter.ofPattern("hh 'o''clock' a, zzzz", Locale.ENGLISH);
    System.out.println(ZonedDateTime.now(ZoneId.of("America/Los_Angeles"))
            .format(formatterWithSingleQuoteInsideSingleQuotes));

02 o'clock AM, Pacific Daylight Time

All of the formatters above can be used for parsing too. For example:

    LocalTime time = LocalTime.parse("16 43' 56\"", formatterWithSingleQuote);
    System.out.println(time);

16:43:56

The SimpleDateFormat class used when this question was asked nearly 10 years ago is notoriously troublesome and long outdated. I recommend that instead you use java.time, the modern Java date and time API. Which is why I demonstrate just that.

Links

Jumbo answered 4/10, 2019 at 9:36 Comment(0)
B
7

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
Boughton answered 26/1, 2010 at 7:56 Comment(0)
B
-4

java.text.SimpleDateFormat

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

You'll get more info here link text

Borscht answered 26/1, 2010 at 8:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.