Formatting Java.util.Date in a Specific Format
In Java, formatting a Date object into a specific string format is a common task. However, when dealing with complex scenarios like sorting dates as Dates rather than Strings, the need arises to parse the string date while maintaining the desired output format.
Consider the following scenario:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); System.out.println(dateFormat.parse("31/05/2011"));
The above code parses the date string "31/05/2011" into a Date object. However, the output format is not the desired "31/05/2011" but rather "Tue May 31 00:00:00 SGT 2011". To overcome this challenge, a simple solution is to use both parse and format methods of SimpleDateFormat:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));
By first parsing the date string into a Date object and then formatting it using the same date format, the desired output format is achieved while still preserving the ability to sort the dates as Dates. This method effectively isolates the formatting task, allowing for more flexibility and control over the final string representation of the date.
The above is the detailed content of How Can I Format a Java Date Object to a Specific String While Preserving its Date Functionality?. For more information, please follow other related articles on the PHP Chinese website!