Java Date Format

In Java, the java.text.SimpleDateFormat class is used to format and parse dates according to a specified pattern. Here’s an example of how to use it:

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

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date object
        Date date = new Date();

        // create a date format object with the desired pattern
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // format the date according to the pattern
        String formattedDate = dateFormat.format(date);

        // print the formatted date
        System.out.println("Formatted Date: " + formattedDate);
    }
}

The output of the above code will be a formatted date string in the specified pattern: Formatted Date: 2023-05-07 16:26:30.

Here are some common patterns used in SimpleDateFormat:

Pattern Meaning
yyyy Year
MM Month (01-12)
dd Day of month (01-31)
HH Hour in day (00-23)
mm Minute in hour (00-59)
ss Second in minute (00-59)
S Millisecond
EEE Day of the week (e.g. Mon, Tue, etc.)
zzz Time zone (e.g. PST, GMT, etc.)

You can customize the pattern to fit your needs. For more information on the available patterns, you can check out the Java documentation.

java.text.DateFormat Fields:

The java.text.DateFormat class is an abstract class that provides methods for formatting and parsing dates and times in a locale-sensitive manner. It defines several fields that can be used to customize the formatting of dates and times. Here are the most common fields:

  • SHORT – A constant indicating a short style of date or time formatting. This is typically a numeric or abbreviated text format.
  • MEDIUM – A constant indicating a medium style of date or time formatting. This is typically a longer, more descriptive format than SHORT.
  • LONG – A constant indicating a long style of date or time formatting. This is typically the most descriptive format, including details such as the time zone and day of the week.
  • FULL – A constant indicating a full style of date or time formatting. This includes all available details, such as the day of the week, month, day, year, and time.

Here’s an example of how to use these fields in DateFormat:

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

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date object
        Date date = new Date();

        // create a date format object with the desired style and locale
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, Locale.US);

        // format the date according to the style and locale
        String formattedDate = dateFormat.format(date);

        // print the formatted date
        System.out.println("Formatted Date: " + formattedDate);
    }
}

The output of the above code will be a formatted date string in the specified style and locale: Formatted Date: May 7, 2023 4:57:12 PM.

Note that the exact format of the output may vary depending on the locale and the implementation of DateFormat used.

java.text.DateFormat Methods:

The java.text.DateFormat class provides methods for formatting and parsing dates and times in a locale-sensitive manner. Here are some of the most commonly used methods:

  1. format(Date date) – Formats a date into a string representation according to the current locale and formatting style.
import java.text.DateFormat;
import java.util.Date;

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date object
        Date date = new Date();

        // create a date format object
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);

        // format the date
        String formattedDate = dateFormat.format(date);

        // print the formatted date
        System.out.println("Formatted Date: " + formattedDate);
    }
}

Output: Formatted Date: May 7, 2023

  1. parse(String source) – Parses a string representation of a date according to the current locale and formatting style.
import java.text.DateFormat;
import java.util.Date;

public class DateFormatExample {
    public static void main(String[] args) throws Exception {
        // create a date format object
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);

        // parse a date string
        Date date = dateFormat.parse("May 7, 2023");

        // print the parsed date
        System.out.println("Parsed Date: " + date);
    }
}

Output: Parsed Date: Sun May 07 00:00:00 GMT 2023

  1. setTimeZone(TimeZone timeZone) – Sets the time zone of this date format object.
import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date object
        Date date = new Date();

        // create a date format object
        DateFormat dateFormat = DateFormat.getDateTimeInstance();

        // set the time zone to UTC
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

        // format the date
        String formattedDate = dateFormat.format(date);

        // print the formatted date
        System.out.println("Formatted Date: " + formattedDate);
    }
}

Output: Formatted Date: Sun May 07 16:02:50 UTC 2023

These are just a few examples of the methods available in DateFormat. For a full list of methods, you can check out the Java documentation.

Java DateFormat Example: Date to String

Here’s an example of how to use DateFormat in Java to format a Date object into a String representation:

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

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date object
        Date date = new Date();

        // create a date format object with the desired format and locale
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);

        // format the date into a string representation
        String formattedDate = dateFormat.format(date);

        // print the formatted date
        System.out.println("Formatted Date: " + formattedDate);
    }
}

In this example, we create a Date object with the current date and time. We then create a DateFormat object using the getDateInstance() method, passing DateFormat.MEDIUM as the format style and Locale.US as the locale. This creates a date format object that will format the date in a medium format suitable for US locales.

We then use the format() method of the DateFormat object to format the Date object into a String representation. Finally, we print the formatted date to the console.

The output of the above code will be a string representation of the current date in the specified format and locale. For example, on May 7, 2023, the output might be Formatted Date: May 7, 2023.

Java DateFormat Example: String to Date

Here’s an example of how to use DateFormat in Java to parse a String representation of a date into a Date object:

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

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date format object with the desired format and locale
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);

        // create a string representation of a date
        String dateString = "May 7, 2023";

        try {
            // parse the string into a date object
            Date date = dateFormat.parse(dateString);

            // print the date object
            System.out.println("Date: " + date);
        } catch (ParseException e) {
            System.err.println("Unable to parse date: " + e.getMessage());
        }
    }
}

In this example, we create a DateFormat object using the getDateInstance() method, passing DateFormat.MEDIUM as the format style and Locale.US as the locale. This creates a date format object that will be able to parse a string representation of a date in the same format used in the previous example.

We then create a string representation of a date using the same format as the date format object. We then use the parse() method of the DateFormat object to parse the string into a Date object. Since parse() can throw a ParseException, we surround the call with a try-catch block to handle any exceptions that might occur.

Finally, we print the Date object to the console. The output of the above code should be a Date object representing May 7, 2023.

Note that the parse() method will only be able to parse a string that matches the specified format and locale. If the string does not match the format, a ParseException will be thrown.

Java DateFormat Example: getTimeInstance(int style, Locale locale):

Here’s an example of how to use DateFormat in Java to format a Date object into a String representation of the time only using the getTimeInstance() method:

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

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date object
        Date date = new Date();

        // create a date format object with the desired format and locale
        DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US);

        // format the time into a string representation
        String formattedTime = timeFormat.format(date);

        // print the formatted time
        System.out.println("Formatted Time: " + formattedTime);
    }
}

In this example, we create a Date object with the current date and time. We then create a DateFormat object using the getTimeInstance() method, passing DateFormat.SHORT as the format style and Locale.US as the locale. This creates a date format object that will format the time in a short format suitable for US locales.

We then use the format() method of the DateFormat object to format the Date object into a String representation of the time only. Finally, we print the formatted time to the console.

The output of the above code will be a string representation of the current time in the specified format and locale. For example, on May 7, 2023 at 10:30:45 AM, the output might be Formatted Time: 10:30 AM.

Java DateFormat Example: getDateInstance(int style):

Here’s an example of how to use DateFormat in Java to format a Date object into a String representation of the date only using the getDateInstance() method:

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

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date object
        Date date = new Date();

        // create a date format object with the desired format and locale
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG);

        // format the date into a string representation
        String formattedDate = dateFormat.format(date);

        // print the formatted date
        System.out.println("Formatted Date: " + formattedDate);
    }
}

In this example, we create a Date object with the current date and time. We then create a DateFormat object using the getDateInstance() method, passing DateFormat.LONG as the format style. This creates a date format object that will format the date in a long format suitable for the default locale.

We then use the format() method of the DateFormat object to format the Date object into a String representation of the date only. Finally, we print the formatted date to the console.

The output of the above code will be a string representation of the current date in the specified format and locale. For example, on May 7, 2023, the output might be Formatted Date: May 7, 2023.

Java DateFormat Example: getDateInstance(int style, Locale locale):

Here’s an example of how to use DateFormat in Java to format a Date object into a String representation of the date only using the getDateInstance() method with a specific locale:

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

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date object
        Date date = new Date();

        // create a date format object with the desired format and locale
        Locale germanLocale = new Locale("de", "DE"); // create a German locale
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, germanLocale);

        // format the date into a string representation
        String formattedDate = dateFormat.format(date);

        // print the formatted date
        System.out.println("Formatted Date: " + formattedDate);
    }
}

In this example, we create a Date object with the current date and time. We then create a Locale object for the German locale using the constructor that takes a language code and a country code. We then create a DateFormat object using the getDateInstance() method, passing DateFormat.FULL as the format style and the German locale as the locale. This creates a date format object that will format the date in a full format suitable for the German locale.

We then use the format() method of the DateFormat object to format the Date object into a String representation of the date only. Finally, we print the formatted date to the console.

The output of the above code will be a string representation of the current date in the specified format and locale. For example, on May 7, 2023, the output might be Formatted Date: Sonntag, 7. Mai 2023.

Java DateFormat Example: getDateTimeInstance(int dateStyle, int timeStyle, Locale locale):

Here’s an example of how to use DateFormat in Java to format a Date object into a String representation of the date and time using the getDateTimeInstance() method with a specific style and locale:

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

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date object
        Date date = new Date();

        // create a date format object with the desired format and locale
        Locale frenchLocale = new Locale("fr", "FR"); // create a French locale
        DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, frenchLocale);

        // format the date and time into a string representation
        String formattedDateTime = dateTimeFormat.format(date);

        // print the formatted date and time
        System.out.println("Formatted Date and Time: " + formattedDateTime);
    }
}

In this example, we create a Date object with the current date and time. We then create a Locale object for the French locale using the constructor that takes a language code and a country code. We then create a DateFormat object using the getDateTimeInstance() method, passing DateFormat.MEDIUM as the date format style, DateFormat.SHORT as the time format style, and the French locale as the locale. This creates a date format object that will format the date in a medium format and the time in a short format suitable for the French locale.

We then use the format() method of the DateFormat object to format the Date object into a String representation of the date and time. Finally, we print the formatted date and time to the console.

The output of the above code will be a string representation of the current date and time in the specified format and locale. For example, on May 7, 2023 at 10:30:45 AM, the output might be Formatted Date and Time: 7 mai 2023 10:30.

Java DateFormat Example: getCalender()

In Java, the DateFormat class also provides the getCalendar() method, which returns the Calendar object associated with this DateFormat.

Here’s an example of how to use the getCalendar() method to get the Calendar object associated with a DateFormat instance:

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

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date object
        Date date = new Date();

        // create a date format object with the desired format and locale
        Locale usLocale = new Locale("en", "US"); // create a US locale
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, usLocale);

        // get the calendar object associated with the date format
        Calendar calendar = dateFormat.getCalendar();
        calendar.setTime(date);

        // print the calendar object's fields
        System.out.println("Year: " + calendar.get(Calendar.YEAR));
        System.out.println("Month: " + calendar.get(Calendar.MONTH));
        System.out.println("Day of Month: " + calendar.get(Calendar.DAY_OF_MONTH));
    }
}

In this example, we create a Date object with the current date and time. We then create a Locale object for the US locale using the constructor that takes a language code and a country code. We then create a DateFormat object using the getDateInstance() method, passing DateFormat.FULL as the format style and the US locale as the locale. This creates a date format object that will format the date in a full format suitable for the US locale.

We then use the getCalendar() method of the DateFormat object to get the Calendar object associated with the date format. We set the time of the Calendar object to the time of the Date object using the setTime() method of the Calendar object.

Finally, we print the fields of the Calendar object to the console using the get() method. We print the year, month, and day of the month fields, but there are many other fields that can be accessed using this method.

The output of the above code will be the current year, month, and day of the month in the specified format and locale. For example, on May 7, 2023, the output might be:

Year: 2023
Month: 4
Day of Month: 7

Note that the month field is zero-based, so 4 corresponds to May.

Java DateFormat Example: getNumberFormat()

In Java, the DateFormat class also provides the getNumberFormat() method, which returns the NumberFormat object associated with this DateFormat.

Here’s an example of how to use the getNumberFormat() method to get the NumberFormat object associated with a DateFormat instance:

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

public class DateFormatExample {
    public static void main(String[] args) {
        // create a date format object with the desired format and locale
        Locale usLocale = new Locale("en", "US"); // create a US locale
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, usLocale);

        // get the number format object associated with the date format
        NumberFormat numberFormat = dateFormat.getNumberFormat();

        // format a number using the number format object
        double number = 1234567.89;
        String formattedNumber = numberFormat.format(number);

        // print the formatted number
        System.out.println("Formatted Number: " + formattedNumber);
    }
}

In this example, we create a Locale object for the US locale using the constructor that takes a language code and a country code. We then create a DateFormat object using the getDateInstance() method, passing DateFormat.MEDIUM as the format style and the US locale as the locale. This creates a date format object that will format the date in a medium format suitable for the US locale.

We then use the getNumberFormat() method of the DateFormat object to get the NumberFormat object associated with the date format.

Finally, we use the format() method of the NumberFormat object to format a number (in this case, 1234567.89) using the number format object. We then print the formatted number to the console.

The output of the above code will be the formatted number in the specified format and locale. For example, using the US locale, the output might be:

Formatted Number: 1,234,567.89

Note that the exact output may depend on the locale and the number being formatted.