DateFormat
About
The DateFormat class in Java is part of the java.text package and provides a mechanism to format and parse dates and times in a locale-sensitive way. It allows developers to convert Date objects to String representations and vice versa.
DateFormatis an abstract class that provides the formatting and parsing capabilities for dates and times.It is locale-sensitive, allowing dates and times to be displayed in formats familiar to the user's region.
The
SimpleDateFormatsubclass is commonly used for custom date and time patterns.
Features
Locale-Sensitive Formatting: Adapts date and time formats to different regional conventions.
Predefined Formats: Includes predefined styles such as
SHORT,MEDIUM,LONG, andFULLfor formatting dates and times.Parsing Support: Converts formatted strings back into
Dateobjects.Thread-Safe Alternatives:
DateFormatis not thread-safe, but it can be made thread-safe using thread-local storage or external synchronization.Customizability: Subclasses like
SimpleDateFormatallow custom date and time patterns.
Declaration
To use the DateFormat class, we must import it from the java.text package:
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;Common Methods
Static Factory Methods:
getDateInstance(): Returns a date formatter for the default locale.getTimeInstance(): Returns a time formatter for the default locale.getDateTimeInstance(): Returns a date and time formatter for the default locale.getInstance(): Returns a default date and time formatter.
Formatting Methods:
format(Date date): Converts aDateobject into a formattedString.
Parsing Methods:
parse(String source): Parses aStringinto aDateobject.
Customization Methods:
setCalendar(Calendar newCalendar): Sets the calendar to be used for formatting.setLenient(boolean lenient): Specifies whether the parser is lenient in interpreting dates.
Usage
Formatting Dates and Times
Output:
Formatting Date and Time for Different Locales
Output:
Parsing Dates
Output:
Using SimpleDateFormat for Custom Patterns
SimpleDateFormat for Custom PatternsOutput:
Applications and Real-World Usage
Date and Time Display: Format dates and times for user interfaces in locale-sensitive ways.
Internationalization: Adapts date and time formats to the user's locale, making applications globally usable.
Log Timestamps: Format timestamps in logs for readability and analysis.
Custom Formats for Reports: Use
SimpleDateFormatto apply specific patterns for generating reports.Parsing Input: Parse user-inputted date strings for data processing and storage.
Last updated