Formatting Java.util.Date in a Custom Format
It is common to encounter scenarios where you need to display a Java.util.Date in a specific format. By utilizing the SimpleDateFormat class, you can control how your date is presented. However, if you require the date to be sorted as a Date, using parse alone may not suffice.
Consider the following example, where parsing a date using SimpleDateFormat("dd/MM/yyyy") results in an unexpected output format:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); System.out.println(dateFormat.parse("31/05/2011"));
This code will output:
Tue May 31 00:00:00 SGT 2011
To achieve the desired output of "31/05/2011", while maintaining the ability to sort dates, you can utilize the format() method after parsing:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));
This solution effectively parses the date using the specified format and then formats it again using the same format, resulting in the desired output.
The above is the detailed content of How Can I Format a Java.util.Date in a Custom Format While Maintaining Sortability?. For more information, please follow other related articles on the PHP Chinese website!