Back to: Java Tutorials
Step-by-step tutorial on how to handle date formats in Java:
- Import the
java.util.Dateandjava.text.SimpleDateFormatpackages: To handle date formats in Java, you need to import thejava.util.Datepackage to create aDateobject, and thejava.text.SimpleDateFormatpackage to format the date. You can do this by adding the following lines at the top of your Java file:
import java.util.Date;
import java.text.SimpleDateFormat;
- Create a
Dateobject: To handle the date format of a specific date, you need to create aDateobject that represents that date. You can do this by using one of theDateclass’s constructors. For example, to create aDateobject representing the current date and time, you can use the following code:
Date currentDate = new Date();
This will create a new Date object that represents the current date and time.
- Create a
SimpleDateFormatobject: To handle the date format of aDateobject, you need to create aSimpleDateFormatobject that defines the format you want to use. For example, to format the date as “dd/MM/yyyy HH:mm:ss”, you can use the following code:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
This will create a new SimpleDateFormat object that uses the specified format string.
- Format the
Dateobject: To format theDateobject using theSimpleDateFormatobject, you can use theformat()method. For example, to format thecurrentDateobject using thedateFormatobject, you can use the following code:
String formattedDate = dateFormat.format(currentDate);
This will create a new String object that contains the formatted date value.
- Parse a
Stringto aDateobject: To parse aStringthat represents a date to aDateobject, you can use theparse()method of theSimpleDateFormatclass. For example, to parse theString“12/02/2023 12:34:56” to aDateobject using thedateFormatobject, you can use the following code:
String dateString = "12/02/2023 12:34:56";
Date parsedDate = dateFormat.parse(dateString);
This will create a new Date object that represents the parsed date value.
- Handle exceptions: When parsing a
Stringto aDateobject, it’s important to handle exceptions that may occur. For example, if theStringdoesn’t match the expected format, aParseExceptionwill be thrown. You can handle this exception using atry-catchblock. Here’s an example:
String dateString = "12/02/23 12:34:56";
try {
Date parsedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
In this example, if the String “12/02/23 12:34:56” is parsed using the dateFormat object, a ParseException will be thrown because the year is represented with only two digits instead of four. The catch block will handle this exception and print the stack trace to the console.
Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.
Follow us on social media
Follow Author
