How to Convert a java.util.Date to a String in Java
Problem:
You need to convert a java.util.Date object to a formatted String in Java, specifically in the format "2010-05-30 22:15:52".
Solution:
To convert a java.util.Date to a String in Java, you can use the DateFormat.format() method. This method takes a Date object and a formatting pattern as input and returns a formatted String.
Here's an example:
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);
This code will print the current date and time in the specified format:
Today is: 05/30/2010 22:15:52
Source:
http://www.kodejava.org/examples/86.html
The above is the detailed content of How to Format a java.util.Date Object as a String in Java?. For more information, please follow other related articles on the PHP Chinese website!