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.example.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.toString());
        }

        // 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: 10-Apr-2018
Default time format: 10:18:11 PM

France
--------------------------------
Default date format: 10 avr. 2018
Default time format: 22:18:11

Germany
--------------------------------
Default date format: 10.04.2018
Default time format: 22:18:11

United States
--------------------------------
Default date format: Apr 10, 2018
Default time format: 10:18:11 PM

Japan
--------------------------------
Default date format: 2018/04/10
Default time format: 22:18:11

date time format in Italy: 10-apr-2018 22.18.11

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.example.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.example.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 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.example.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.example.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 includes the correct thousands 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.example.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.example.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 have 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 $10.00 and $75.00 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 a time information.

package org.kodejava.example.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 nextWeek = 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, nextWeek);
        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, nextWeek);
        System.out.println(message);

        // Format a time using a short format (eg. HH:mm am/pm)
        message = MessageFormat.format("Now is {0, time, short} and " +
                "the next 7 hours is {1, time, short}", today, nextWeek);
        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, nextWeek);
        System.out.println(message);

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

        // Format a time using a full format (eg. HH:mm:ss am/pm TIMEZONE).
        message = MessageFormat.format("Now is {0, time, full} and the " +
                "next 7 hours is {1, time, full}", today, nextWeek);
        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, nextWeek);
        System.out.println(message);
    }
}

The above program produces:

Now is 2/15/18, 9:07 PM and the next 7 hours is 2/16/18, 4:07 AM
Now is 9:07:26 PM and the next 7 hours is 4:07:26 AM
Now is 9:07 PM and the next 7 hours is 4:07 AM
Now is 9:07:26 PM and the next 7 hours is 4:07:26 AM
Now is 9:07:26 PM CST and the next 7 hours is 4:07:26 AM CST
Now is 9:07:26 PM China Standard Time and the next 7 hours is 4:07:26 AM China Standard Time
Now is  21:07:26.026 and the next 7 hours is  04:07:26.026

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.example.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 (eg. 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 display 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 2/15/18, 8:57 PM and next week is 2/22/18, 8:57 PM
Today is Feb 15, 2018 and next week is Feb 22, 2018
Today is 2/15/18 and next week is 2/22/18
Today is Feb 15, 2018 and next week is Feb 22, 2018
Today is February 15, 2018 and next week is February 22, 2018
Today is Thursday, February 15, 2018 and next week is Thursday, February 22, 2018
Today is 15-02-2018 and next week is 22-02-2018

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.example.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) = 2018年2月15日
Date format in Chinese (China) = 2018年2月15日
Date format in Korean (South Korea) = 2018년 2월 15일
Date format in Chinese (Taiwan) = 2018年2月15日
Date format in Italian (Italy) = 15 febbraio 2018
Date format in French (France) = 15 février 2018
Date format in German = 15. Februar 2018