How do I get default date and time format for a defined country?

The DateFormat class allows you to format dates and times with predefined styles in a locale-sensitive manner. Formatting dates or times with the DateFormat class is a two-step process.

First, you create a formatter with the getDateInstance() method for formatting date or getTimeInstance() method for formatting time or getDateTimeInstance() when you want formatting both date and time.

Second, you invoke the format method, which returns a String containing the formatted date. The following example formats today’s date and time by calling those two methods.

package org.kodejava.text;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

public class LocaleDateTime {
    public static void main(String[] args) {
        Locale[] locales = {
                Locale.CANADA, Locale.FRANCE, Locale.GERMANY, Locale.US, 
                Locale.JAPAN
        };

        Date today = new Date();
        for (Locale locale : locales) {
            StringBuilder sb = new StringBuilder();
            sb.append(locale.getDisplayCountry()).append(System.lineSeparator());
            sb.append("------------------------").append(System.lineSeparator());

            // Gets a DateFormat instance for the specified locale
            // and format a date object by calling the format method.
            DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
            String date = df.format(today);
            sb.append("Default date format: ").append(date)
                    .append(System.lineSeparator());

            // Gets a DateFormat instance for the specified locale
            // and format a time information by calling the format method.
            DateFormat tf = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
            String time = tf.format(today.getTime());
            sb.append("Default time format: ").append(time)
                    .append(System.lineSeparator());

            System.out.println(sb);
        }

        // Gets date and time formatted value for Italy locale using
        // To display a date and time in the same String, create the
        // formatter with the getDateTimeInstance method.
        // The first parameter is the date style, and the second is
        // the time style. The third parameter is the Locale
        DateFormat dtf = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,
                DateFormat.DEFAULT, Locale.ITALY);
        String datetime = dtf.format(today);

        System.out.println("date time format in " +
                Locale.ITALY.getDisplayCountry() + ": " + datetime);
    }
}

Here are the produces output:

Canada
------------------------
Default date format: Oct. 19, 2021
Default time format: 6:11:45 a.m.

France
------------------------
Default date format: 19 oct. 2021
Default time format: 06:11:45

Germany
------------------------
Default date format: 19.10.2021
Default time format: 06:11:45

United States
------------------------
Default date format: Oct 19, 2021
Default time format: 6:11:45 AM

Japan
------------------------
Default date format: 2021/10/19
Default time format: 6:11:45

date time format in Italy: 19 ott 2021, 06:11:45

How do I change the currency symbol?

This example show you how to change the currency symbol for the defined locale using the DecimalFormatSymbols.setCurrencySymbol() method. After changing the currency symbol, the DecimalFormatSymbols instance is passed to the DecimalFormat object which does the formatting.

package org.kodejava.text;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;

public class CurrencyFormatSymbols {
    public static void main(String[] args) {
        double number = 123456.789;

        Locale[] locales = {
                Locale.CANADA, Locale.GERMANY, Locale.UK, Locale.ITALY, Locale.US
        };

        String[] symbols = {"CAD", "EUR", "GBP", "ITL", "USD"};

        for (int i = 0; i < locales.length; i++) {
            // Gets currency's formatted value for each locale
            // without change the currency symbol
            DecimalFormat formatter =
                    (DecimalFormat) NumberFormat.getCurrencyInstance(locales[i]);
            String before = formatter.format(number);

            // Create a DecimalFormatSymbols for each locale and sets
            // its new currency symbol.
            DecimalFormatSymbols symbol = new DecimalFormatSymbols(locales[i]);
            symbol.setCurrencySymbol(symbols[i]);

            // Set the new DecimalFormatSymbols into formatter object.
            formatter.setDecimalFormatSymbols(symbol);

            // Gets the formatted value
            String after = formatter.format(number);
            System.out.println(locales[i].getDisplayCountry() +
                    " | before: " + before + " | after: " + after);
        }
    }
}

Here is are the result of our program:

Canada | before: $123,456.79 | after: CAD123,456.79
Germany | before: 123.456,79 € | after: 123.456,79 EUR
United Kingdom | before: £123,456.79 | after: GBP123,456.79
Italy | before: € 123.456,79 | after: ITL 123.456,79
United States | before: $123,456.79 | after: USD123,456.79

How do I change number format symbols?

You can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers. These symbols include the decimal separator which can be changed using the setDecimalSeparator(), the grouping separator which can be change using the setGroupingSeparator() method. You can also alter the minus sign, and the percent sign, among others.

package org.kodejava.text;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

public class NumberFormatSymbol {
    public static void main(String[] args) {
        DecimalFormat formatter;
        String pattern = "###,###.##";
        double number = 123456.789;

        // Create a DecimalFormatSymbols object for the United States
        // locale.
        DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);

        // Create a format object with the given pattern without
        // change the locale dfs then format the given value.
        formatter = new DecimalFormat(pattern);
        String before = formatter.format(number);

        // Change the decimal separator and grouping separator symbol.
        dfs.setDecimalSeparator(',');
        dfs.setGroupingSeparator('.');
        dfs.setMinusSign('-');
        dfs.setPercent('%');

        // Create a format object with the given pattern and symbol
        // then format the given value.
        formatter = new DecimalFormat(pattern, dfs);
        String after = formatter.format(number);

        System.out.println("before: " + before + " | after: " + after);
    }
}

How do I change DecimalFormat pattern?

To change the pattern use by the DecimalFormat when formatting a number we can use the DecimalFormat.applyPattern() method call. In this example we use three different patterns to format the given input number. The pattern determines what the formatted number looks like.

package org.kodejava.text;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class FormatterPattern {
    public static void main(String[] args) {
        String[] patterns = {"###,###,###.##", "000000000.00", "$###,###.##"};

        double before = 1234567.899;

        // To obtain a NumberFormat for a specific locale,
        // including the default locale, call one of NumberFormat's
        // factory methods, such as getNumberInstance(). Then cast
        // it into a DecimalFormat.
        DecimalFormat format =
                (DecimalFormat) NumberFormat.getNumberInstance(Locale.UK);
        for (String pattern : patterns) {
            // Apply the given pattern to this Format object
            format.applyPattern(pattern);

            // Gets the formatted value
            String after = format.format(before);

            System.out.printf("Input: %s, Pattern: %s, Output: %s%n",
                    before, pattern, after);
        }
    }
}

The output of the program shown below:

Input: 1234567.899, Pattern: ###,###,###.##, Output: 1,234,567.9
Input: 1234567.899, Pattern: 000000000.00, Output: 001234567.90
Input: 1234567.899, Pattern: $###,###.##, Output: $1,234,567.9

How do I format number as percentage string?

The NumberFormat.getPercentInstance() method returns a percentage format for the specified locale. In this example we will format the number as percentage using the Locale.US locale.

package org.kodejava.text;

import java.text.NumberFormat;
import java.util.Locale;

public class LocalePercentageFormat {
    public static void main(String[] args) {
        // Format percentage for Locale.US locale with this formatter,
        // a decimal fraction such as 0.75 is displayed as 75%
        double number = 0.25;
        NumberFormat format = NumberFormat.getPercentInstance(Locale.US);
        String percentage = format.format(number);
        System.out.println(number + " in percentage = " + percentage);
    }
}

The following line is the output of the program:

0.25 in percentage = 25%

How do I format a number as currency string?

Creating a financial application requires you to format number as a currency. It should include the correct thousand separator, decimal separator and the currency symbol. For this purpose you can use the NumberFormat.getCurrencyInstance() method and pass the correct Locale to get the currency format that you want.

package org.kodejava.text;

import java.text.NumberFormat;
import java.util.Locale;

public class LocaleCurrencyFormat {
    public static void main(String[] args) {
        Double number = 1500D;

        // Format currency for Canada locale in Canada locale, 
        // the decimal point symbol is a comma and currency
        // symbol is $.
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.CANADA);
        String currency = format.format(number);
        System.out.println("Currency in Canada : " + currency);

        // Format currency for Germany locale in German locale,
        // the decimal point symbol is a dot and currency symbol
        // is €.
        format = NumberFormat.getCurrencyInstance(Locale.GERMANY);
        currency = format.format(number);
        System.out.println("Currency in Germany: " + currency);
    }
}

Here is an output for the currency format using the Locale.CANADA and Locale.GERMANY.

Currency in Canada : $1,500.00
Currency in Germany: 1.500,00 €

How do I format a message that contains number information?

This example show you how to use java.text.MessageFormat class to format a message that contains numbers.

package org.kodejava.text;

import java.text.MessageFormat;
import java.util.Locale;

public class MessageFormatNumber {
    public static void main(String[] args) {

        // Set the Locale for the MessageFormat.
        Locale.setDefault(Locale.US);

        // Use the default formatting for number.
        String message = MessageFormat.format("This is a {0} and {1} numbers",
                10, 75);
        System.out.println(message);

        // This line has the same format as above.
        message = MessageFormat.format("This is a {0,number} and {1,number} " +
                "numbers", 10, 75);
        System.out.println(message);

        // Format a number with 2 decimal digits.
        message = MessageFormat.format("This is a formatted {0, number,#.##} " +
                "and {1, number,#.##} numbers", 25.7575, 75.2525);
        System.out.println(message);

        // Format a number as currency.
        message = MessageFormat.format("This is a formatted currency " +
                        "{0,number,currency} and {1,number,currency} numbers",
                25.7575, 25.7575);
        System.out.println(message);

        // Format numbers in percentage.
        message = MessageFormat.format("This is a formatted percentage " +
                "{0,number,percent} and {1,number,percent} numbers", 0.10, 0.75);
        System.out.println(message);
    }
}

The result of the program are the following lines:

This is a 10 and 75 numbers
This is a 10 and 75 numbers
This is a formatted 25.76 and 75.25 numbers
This is a formatted currency $25.76 and $25.76 numbers
This is a formatted percentage 10% and 75% numbers

How do I format a message that contains time information?

Here we demonstrate how to use the java.text.MessageFormat class to format a message contains time information.

package org.kodejava.text;

import java.util.Date;
import java.util.Calendar;
import java.util.Locale;
import java.text.MessageFormat;

public class MessageFormatTime {
    public static void main(String[] args) {
        Date today = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, 7);

        Date next7Hours = calendar.getTime();

        // We want the message to be is Locale.US
        Locale.setDefault(Locale.US);

        // Format a time including date information.
        String message = MessageFormat.format("Now is {0} and the next " +
                "7 hours is {1}", today, next7Hours);
        System.out.println(message);

        // Format a time and display only the time portion
        message = MessageFormat.format("Now is {0, time} and the next " +
                "7 hours is {1, time}", today, next7Hours);
        System.out.println(message);

        // Format a time using a short format (e.g. HH:mm am/pm)
        message = MessageFormat.format("Now is {0, time, short} and " +
                "the next 7 hours is {1, time, short}", today, next7Hours);
        System.out.println(message);

        // Format a time using a medium format (eg. HH:mm:ss am/pm).
        message = MessageFormat.format("Now is {0, time, medium} and " +
                "the next 7 hours is {1, time, medium}", today, next7Hours);
        System.out.println(message);

        // Format a time using a long format (e.g. HH:mm:ss am/pm TIMEZONE).
        message = MessageFormat.format("Now is {0, time, long} and the " +
                "next 7 hours is {1, time, long}", today, next7Hours);
        System.out.println(message);

        // Format a time using a full format (e.g. HH:mm:ss am/pm TIMEZONE).
        message = MessageFormat.format("Now is {0, time, full} and the " +
                "next 7 hours is {1, time, full}", today, next7Hours);
        System.out.println(message);

        // Format a time using a custom pattern.
        message = MessageFormat.format("Now is {0, time, HH:mm:ss.sss} " +
                "and the next 7 hours is {1, time, HH:mm:ss.sss}", today, next7Hours);
        System.out.println(message);
    }
}

The above program produces:

Now is 10/8/21, 9:38 PM and the next 7 hours is 10/9/21, 4:38 AM
Now is 9:38:10 PM and the next 7 hours is 4:38:10 AM
Now is 9:38 PM and the next 7 hours is 4:38 AM
Now is 9:38:10 PM and the next 7 hours is 4:38:10 AM
Now is 9:38:10 PM CST and the next 7 hours is 4:38:10 AM CST
Now is 9:38:10 PM China Standard Time and the next 7 hours is 4:38:10 AM China Standard Time
Now is  21:38:10.010 and the next 7 hours is  04:38:10.010

How do I format a message that contains date information?

This example demonstrate how you can use the java.text.MessageFormat class to format a message with a date information in it.

package org.kodejava.text;

import java.util.Date;
import java.util.Calendar;
import java.util.Locale;
import java.text.MessageFormat;

public class MessageFormatDate {
    public static void main(String[] args) {
        Date today = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7);

        Date nextWeek = calendar.getTime();

        // We want the message to be is Locale.US
        Locale.setDefault(Locale.US);

        // Format a date, the time value is included
        String message = MessageFormat.format("Today is {0} and next " +
                "week is {1}", today, nextWeek);
        System.out.println(message);

        // Format a date and display only the date portion
        message = MessageFormat.format("Today is {0,date} and next " +
                "week is {1,date}", today, nextWeek);
        System.out.println(message);

        // Format a date using a short format (e.g. dd/MM/yyyy)
        message = MessageFormat.format("Today is {0,date,short} and " +
                "next week is {1,date,short}", today, nextWeek);
        System.out.println(message);

        // Format a date using a medium format, it displays the month long-name,
        // but using a two digit date and year.
        message = MessageFormat.format("Today is {0,date,medium} and " +
                "next week is {1,date,medium}", today, nextWeek);
        System.out.println(message);

        // Format a date using a long format, two digit for date, a long month
        // name and a four digit year.
        message = MessageFormat.format("Today is {0,date,long} and " +
                "next week is {1,date,long}", today, nextWeek);
        System.out.println(message);

        // Format a date using a full format, the same as above plus a full day
        // name.
        message = MessageFormat.format("Today is {0,date,full} and " +
                "next week is {1,date,full}", today, nextWeek);
        System.out.println(message);

        // Format a date using a custom pattern.
        message = MessageFormat.format("Today is {0,date,dd-MM-yyyy} and " +
                "next week is {1,date,dd-MM-yyyy}", today, nextWeek);
        System.out.println(message);
    }
}

The above program produces:

Today is 10/8/21, 9:35 PM and next week is 10/15/21, 9:35 PM
Today is Oct 8, 2021 and next week is Oct 15, 2021
Today is 10/8/21 and next week is 10/15/21
Today is Oct 8, 2021 and next week is Oct 15, 2021
Today is October 8, 2021 and next week is October 15, 2021
Today is Friday, October 8, 2021 and next week is Friday, October 15, 2021
Today is 08-10-2021 and next week is 15-10-2021

How do I format date using a locale based format?

The code below demonstrate how to format date information for a specific locale. In the example utilize the java.text.SimpleDateFormat class.

package org.kodejava.text;

import java.util.Locale;
import java.util.Date;
import java.text.SimpleDateFormat;

public class FormatDateLocale {
    public static void main(String[] args) {
        // Defines an array of Locale we are going to use for
        // formatting date information.
        Locale[] locales = new Locale[] {
            Locale.JAPAN,
            Locale.CHINA,
            Locale.KOREA,
            Locale.TAIWAN,
            Locale.ITALY,
            Locale.FRANCE,
            Locale.GERMAN
        };

        // Get an instance of current date time
        Date today = new Date();

        // Iterates the entire Locale defined above and create a long
        // formatted date using the SimpleDateFormat.getDateInstance()
        // with the format, the Locale and the date information.
        for (Locale locale : locales) {
            System.out.printf("Date format in %s = %s%n",
                locale.getDisplayName(), SimpleDateFormat.getDateInstance(
                    SimpleDateFormat.LONG, locale).format(today));
        }
    }
}

The result of our code are:

Date format in Japanese (Japan) = 2021年10月6日
Date format in Chinese (China) = 2021年10月6日
Date format in Korean (South Korea) = 2021년 10월 6일
Date format in Chinese (Taiwan) = 2021年10月6日
Date format in Italian (Italy) = 6 ottobre 2021
Date format in French (France) = 6 octobre 2021
Date format in German = 6. Oktober 2021