Home > Java > javaTutorial > How Can I Format a Java.util.Date in a Custom Format While Maintaining Sortability?

How Can I Format a Java.util.Date in a Custom Format While Maintaining Sortability?

Mary-Kate Olsen
Release: 2024-12-28 11:30:43
Original
735 people have browsed it

How Can I Format a Java.util.Date in a Custom Format While Maintaining Sortability?

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"));
Copy after login

This code will output:

Tue May 31 00:00:00 SGT 2011
Copy after login

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")));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template