Back to: Java Tutorials
Step-by-step tutorial on how to handle date formats in Java:
- Import the
java.util.Date
andjava.text.SimpleDateFormat
packages: To handle date formats in Java, you need to import thejava.util.Date
package to create aDate
object, and thejava.text.SimpleDateFormat
package 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
Date
object: To handle the date format of a specific date, you need to create aDate
object that represents that date. You can do this by using one of theDate
class’s constructors. For example, to create aDate
object 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
SimpleDateFormat
object: To handle the date format of aDate
object, you need to create aSimpleDateFormat
object 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
Date
object: To format theDate
object using theSimpleDateFormat
object, you can use theformat()
method. For example, to format thecurrentDate
object using thedateFormat
object, 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
String
to aDate
object: To parse aString
that represents a date to aDate
object, you can use theparse()
method of theSimpleDateFormat
class. For example, to parse theString
“12/02/2023 12:34:56” to aDate
object using thedateFormat
object, 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
String
to aDate
object, it’s important to handle exceptions that may occur. For example, if theString
doesn’t match the expected format, aParseException
will be thrown. You can handle this exception using atry-catch
block. 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