-3

I need to print a stored date (documentDate) in a specific locales format (localeIreland), so far I can only get it to print today's date with cal.getDate() is it possible to get Calendar to print using a stored date value?

String documentDate = "03/03/2018";
String pattern = "EEEEE MMMMM yyyy";
SimpleDateFormat formatIreland= new SimpleDateFormat(pattern, localeIreland);
Calendar cal = Calendar.getInstance();
System.out.println(formatIreland.format(documentDate));

This will only print out today's date.

System.out.println(formatIreland.format(cal.getDate()));
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Ninja2k
  • 819
  • 3
  • 9
  • 34
  • 1
    You need to parse the documentDate to a Date first, using the appropriate pattern, then format the obtained Date. Please, forget about Calendar, SimpleDateFormat and Date. Use a LocalDate and a DateTimeFormat, both part of the java.time API introduced in Java 8. Or use Joda-time or the threeten backport equivalents if stuck in previous versions of Java. – JB Nizet Mar 03 '18 at 17:13
  • You need to know (and specify) the format of your document date: dd/MM/yyyy or MM/dd/yyyy. – Ole V.V. Mar 03 '18 at 19:02
  • What did your research bring up? In what way was it insufficient? Surely how to handle a date string like 03/03/2018 has been treated in many posts already. – Ole V.V. Mar 03 '18 at 19:05
  • @Ole V.V Can you show me a post where this has been done using localisation? I did specify the format above, if you try it with cal.getDate() it will work just fine, it gives the correct format. – Ninja2k Mar 03 '18 at 19:15
  • @JB Nizet Bur Oracle say Date() is depreciated, they recommend calendar. – Ninja2k Mar 03 '18 at 19:35
  • @Ninja2k That’s not exactly true. Most (not all) `Date` methods and constructors have been deprecated in favour of `Calendar` since Java 1.1. Today (since Java 8, March 2014) Oracle recommends java.time, the modern Java date and time API (and not `Calendar`). See [the Oracle tutorial](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 03 '18 at 19:37
  • 2
    @Ninja2k here's what my comment says: *Please, forget about Calendar, SimpleDateFormat and Date. Use a LocalDate and a DateTimeFormat*. So (even if Date is NOT deprecated), I advised you to NOT use it, and use LocalDate instead. – JB Nizet Mar 03 '18 at 19:38
  • 1
    How to parse a date string (which is the part you are missing): [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion). How to format with localisation: For example [SimpleDateFormat and locale based format string](https://stackoverflow.com/questions/1661325/simpledateformat-and-locale-based-format-string). There are many others. – Ole V.V. Mar 03 '18 at 19:46
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). For your problem, specifically `LocalDate`. – Basil Bourque Mar 04 '18 at 20:15

2 Answers2

2
    DateTimeFormatter docDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");

    String documentDate = "03/03/2018";
    DateTimeFormatter formatIreland = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)
            .withLocale(localeIreland);
    System.out.println(LocalDate.parse(documentDate, docDateFormatter).format(formatIreland));

On my computer this just printed

Dé Sathairn 3 Márta 2018

Changing the date format from one string to another is a two-step process and generally requires two formatters: You use one formatter for parsing the original string into a date-time object (here a LocalDate) and then the second formatter for formatting into the desired format.

The recommended way of formatting for a particular locale is through the built-in locale-specific formats. This is what the combination of DateTimeFormatter.ofLocalizedDate and withLocale gives you.

If your Irish users insist, you may of course specify a format yourself like you do in the question:

    String pattern = "EEEE MMMM yyyy";
    DateTimeFormatter formatIreland = DateTimeFormatter.ofPattern(pattern, localeIreland);

With this change the output on my computer is

Dé Sathairn Márta 2018

(To me it looks a bit funny without the day of month, but you can have it the way you want.)

I am using and warmly recommending java.time, the modern Java date and time API. The date-time classes you used, SimpleDateFormat and Calendar, are long outdated, and the former in particular notoriously troublesome. The modern classes are so much nicer to work with. And LocalDate seems to match your requirements exactly since it is a date without time-of-day.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • OMG I cannot believe how hard they make this, just to print out the date. I spent 4 hours going over multiple tutorials and APIs, some using Date, others Calendar, none doing exactly what I need, and I haven't even started on my bundles, a nightmare.Thanks for that! I will take this and study the new stuff in when I am finished with the rest of my program. – Ninja2k Mar 03 '18 at 20:10
  • You can make it a bit easier for yourself if you can store your document date either as a `LocalDate` object (or get such from your database; JDBC or JPA are happy to convert for you) or at least in ISO 8601 format (`2018-03-03`), since `LocalDate` parses this format without an explicit formatter. – Ole V.V. Mar 03 '18 at 20:31
  • 1
    @Ninja2k Yes, the legacy date-time classes such as `Date` and `Calendar` are a bloody awful wretched mess. The *java.time* classes are the opposite: clean, elegant design emanating from a profound understanding of the tricky issues involved with date-time handling. But you do need to spend a bit of time and study to understand the core ideas. – Basil Bourque Mar 03 '18 at 21:04
  • I'd like to see your definition of `localeIreland`. – Basil Bourque Mar 04 '18 at 20:34
  • @BasilBourque I didn’t know what the OP used and didn’t consider it important for the demonstration. I used `Locale.forLanguageTag("ga-IE")`.Thanks for the suggestions in your answer. – Ole V.V. Mar 05 '18 at 04:27
-1

The accepted Answer by Ole V.V. is correct.

Peruse all localized formats

If you want to peruse all the localized formats for all the known time zones, here is some code to dump example values to console.

Use DateTimeFormatter to automatically localize. To localize, specify:

  • FormatStyle to determine how long or abbreviated should the string be.
  • Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Example:

Locale locale = Locale.CANADA_FRENCH ; 
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale );
String output = localDate.format( f );

Specify all format styles.

EnumSet.allOf( FormatStyle.class ) 

[FULL, LONG, MEDIUM, SHORT]

Collect the Locale objects you want to try. You could get a list of all known locales.

   Locale[] locales = Locale.getAvailableLocales();

Or specify just a few locales.

List < Locale > locales = new ArrayList <>( 3 );
locales.add( Locale.CANADA_FRENCH );       // French, Québec Canada
locales.add( new Locale( "ga" , "IE" ) );  // Irish, Ireland
locales.add( new Locale( "en" , "IE" ) );  // English, Ireland
locales.add( Locale.US );                  // English, United States

Complete example code.

LocalDate ld = LocalDate.of( 2018 , Month.MARCH , 23 );

List < Locale > locales = new ArrayList <>( 3 );
locales.add( Locale.CANADA_FRENCH );
locales.add( new Locale( "ga" , "IE" ) );
locales.add( new Locale( "en" , "IE" ) );
locales.add( Locale.US );

for ( Locale locale : locales )
{
    System.out.println( "------|  LOCALE: " + locale + " — " + locale.getDisplayName() + "  |----------------------------------" + System.lineSeparator() );

    for ( FormatStyle style : EnumSet.allOf( FormatStyle.class ) )
    {
        DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( style ).withLocale( locale );
        String output = ld.format( f );
        System.out.println( output );
    }
    System.out.println( "" );
}
System.out.println( "« fin »" + System.lineSeparator() );

Output for our few locales.

------|  LOCALE: fr_CA — French (Canada)  |----------------------------------

vendredi 23 mars 2018
23 mars 2018
23 mars 2018
18-03-23

------|  LOCALE: ga_IE — Irish (Ireland)  |----------------------------------

Dé hAoine 23 Márta 2018
23 Márta 2018
23 Márta 2018
23/03/2018

------|  LOCALE: en_IE — English (Ireland)  |----------------------------------

Friday 23 March 2018
23 March 2018
23 Mar 2018
23/03/2018

------|  LOCALE: en_US — English (United States)  |----------------------------------

Friday, March 23, 2018
March 23, 2018
Mar 23, 2018
3/23/18

« fin »

Output for first 8 of all 736 locales (in Java 9.0.4). (The full content of about 120K in text is too much for Stack Overflow.)

------|  LOCALE:  —   |----------------------------------

2018 Mar 23, Fri
2018 Mar 23
2018 Mar 23
2018-03-23

------|  LOCALE: nn — Norwegian Nynorsk  |----------------------------------

fredag 23. mars 2018
23. mars 2018
23. mars 2018
23.03.2018

------|  LOCALE: ar_JO — Arabic (Jordan)  |----------------------------------

الجمعة، 23 آذار، 2018
23 آذار، 2018
23‏/03‏/2018
23‏/3‏/2018

------|  LOCALE: bg — Bulgarian  |----------------------------------

петък, 23 март 2018 г.
23 март 2018 г.
23.03.2018 г.
23.03.18 г.

------|  LOCALE: kea — Kabuverdianu  |----------------------------------

sesta-fera, 23 di Marsu di 2018
23 di Marsu di 2018
23 Mar 2018
23/3/2018

------|  LOCALE: zu — Zulu  |----------------------------------

ULwesihlanu, Mashi 23, 2018
Mashi 23, 2018
Mas 23, 2018
3/23/18

------|  LOCALE: am_ET — Amharic (Ethiopia)  |----------------------------------

ዓርብ ፣23 ማርች 2018
23 ማርች 2018
23 ማርች 2018
23/03/2018

------|  LOCALE: fr_DZ — French (Algeria)  |----------------------------------

vendredi 23 mars 2018
23 mars 2018
23 mars 2018
23/03/2018

…
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154