Home >Java >javaTutorial >How to Convert a java.util.Date Object to a String in Java?
When working with date objects in Java, it is often necessary to convert them to string representations for display or storage. This tutorial outlines how to achieve this conversion, focusing on the java.util.Date class and the DateFormat API.
The DateFormat class provides a variety of methods for formatting date objects as strings. The format method takes a Date object as an argument and returns a string representation according to a specified pattern.
String pattern = "MM/dd/yyyy HH:mm:ss"; // Create an instance of SimpleDateFormat used for formatting // the string representation of date according to the chosen pattern DateFormat df = new SimpleDateFormat(pattern); // Get the today date using Calendar object. Date today = Calendar.getInstance().getTime(); // Using DateFormat format method we can create a string // representation of a date with the defined format. String todayAsString = df.format(today); // Print the result! System.out.println("Today is: " + todayAsString);
In this example, a SimpleDateFormat object is created with a specified pattern of "MM/dd/yyyy HH:mm:ss", which corresponds to the desired output format. The format method is then used to convert the Date object representing today's date to a string using the provided pattern. The output string will be printed, resulting in a string representation of the date in the specified format.
The above is the detailed content of How to Convert a java.util.Date Object to a String in Java?. For more information, please follow other related articles on the PHP Chinese website!