javadatedatetimedeprecatedjava.util.date

Why Date class does not support Internationalization?


I was going through the different ways that we can get Date and Time in java, while reading the documentation could not understand what the below quote mean.

Unfortunately, the API for these functions was not amenable to internationalization.

The above quote is from documentation of Date class of java. What does that mean ?? Is this the reason why the methods of the Date class were deprecated?


Solution

  • tl;dr

    Use only java.time classes. Never use Date/Calendar etc.

    ZonedDateTime.now(
                    ZoneId.of( "Asia/Tokyo" )
            )
            .format(
                    DateTimeFormatter
                            .ofLocalizedDateTime( FormatStyle.FULL )
                            .withLocale( Locale.GERMANY )
            )
    

    Sonntag, 7. Mai 2023, 04:53:02 Japanische Normalzeit

    Avoid legacy date-time classes

    You asked:

    Is this the reason why the methods of the Date class were deprecated?

    The legacy date-time classes are rife with poor design decisions, written by people who did not understand date-time handling. The lack of internationalization is but one of many problems.

    Trying to understand these legacy classes is a waste of time, unless you want lessons on how to not do proper object-oriented programming. These classes were years ago supplanted by the modern java.time classes defined in JSR 310.

    Use neither of the two Date classes, nor Calendar, SimpleDateFormat, GregorianCalendar, etc. 👉 Use only the date-time classes from the java.time package. Focus your precious learning time on java.time.

    java.time

    The java.time classes provide internationalization through the 👉 DateTimeFormatter class.

    In modern Java, the localization information comes from the Common Locale Data Repository Project (CLDR) published by the Unicode Consortium.

    Here is some example code.

    Capture the current moment as seen in the wall-clock time/calendar used by the people of Japan. For this purpose, use ZonedDateTime class. Specify the time zone of interest by using the ZoneId class.

    ZoneId zoneIdTokyo = ZoneId.of( "Asia/Tokyo" );
    ZonedDateTime zdtTokyo = ZonedDateTime.now( zoneIdTokyo );
    

    Generate text representing that moment using French Canadian localization (human language & cultural norms).

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

    Dump to console.

    System.out.println( "zdtTokyo.toString() = " + zdtTokyo );
    System.out.println( "output = " + output );
    

    When run:

    zdtTokyo.toString() = 2023-05-07T04:47:54.551174+09:00[Asia/Tokyo]
    output = dimanche 7 mai 2023, 04 h 47 min 54 s heure normale du Japon