2

We create J2SE application that has to format the date and time according to custom the country from which users come from. I want to ask how to solve this thing in Java? Probably I'll use SimpleDateFormat, but I wonder if it is possible to get format string in somehow simpler way than to have all format strings for each country separately.

jnemecz
  • 3,171
  • 8
  • 41
  • 77
  • You can use DateFormat With locale if you have to show the date in same format for each country .i.e . DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date()); – Shehzad Apr 13 '12 at 15:00

2 Answers2

2

DateFormat already allows you to do this - just use DateTimeFormat.getDateTimeInstance(dateStyle, timeStyle, locale) or something similar, depending on your needs.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern Date-Time API:

Use DateTimeFormatter.#ofLocalizedDate to get a locale specific date format for the ISO chronology.

Demo:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtfDateFull = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)
                .localizedBy(new Locale("cs", "CZ"));
        DateTimeFormatter dtfDateMedium = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
                .localizedBy(new Locale("cs", "CZ"));
        DateTimeFormatter dtfDateShort = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
                .localizedBy(new Locale("cs", "CZ"));

        LocalDate date = LocalDate.now(ZoneId.of("Europe/Prague"));

        System.out.println(date.format(dtfDateFull));
        System.out.println(date.format(dtfDateMedium));
        System.out.println(date.format(dtfDateShort));
    }
}

Output from a sample run:

neděle 18. července 2021
18. 7. 2021
18.07.21

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110