How is the dateformat used in Java?
In Java, the DateFormat class is an abstract class used for formatting dates and times. It provides methods for converting date objects into string representations and parsing string representations into date objects.
The main steps to use the DateFormat class are as follows:
- Create a DateFormat object, which can be used with its subclass SimpleDateFormat to specify the date format.
- Create a date format by using the SimpleDateFormat class, with the pattern “yyyy-MM-dd HH:mm:ss”.
- In the above example, the date format is “yyyy-MM-dd HH:mm:ss”, where:
- yyyy: A four-digit year.
- MM: Months in double digits
- dd: Date in two digits
- HH: Double-digit hour (in the 24-hour clock)
- mm: minutes in two digits
- ss: double-digit seconds
- Format the date object as a string.
- Create a new instance of Date to obtain the current date and time. Format the date using the specified date format and then print it out.
- The examples above format the current date and time into a string, and print it out.
- Parse the string into a date object.
- Convert the string “2021-01-01 12:00:00” to a date format and print the parsed date.
- The above example parses the string “2021-01-01 12:00:00” into a date object and prints it out.
It should be noted that the DateFormat class is not thread-safe, so it is recommended to avoid sharing DateFormat objects in a multi-threaded environment.