Home >Java >javaTutorial >How to Format a Java Calendar Date as yyyy-MM-dd?

How to Format a Java Calendar Date as yyyy-MM-dd?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 02:01:08827browse

How to Format a Java Calendar Date as yyyy-MM-dd?

Converting Calendar Date to yyyy-MM-dd Format in Java

In Java programming, a common task is to convert a calendar date into the widely-used yyyy-MM-dd format, often required for comparison and handling in databases.

Issue:

When using the Calendar class to represent a date, it is returned as a Date object. However, when directly converting the Date object to a string, it defaults to a verbose format that includes the time and timezone information, such as "Wed Sep 26 00:00:00 IST 2012." This format is not suitable for comparisons in database criteria, where the expected format is "2012-09-26."

Solution:

To address this issue, we can utilize the SimpleDateFormat class to explicitly format the Date object into the desired yyyy-MM-dd format. Here's how to achieve this:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(cal.getTime());

The formatted date is now in the yyyy-MM-dd format, ensuring proper comparison and handling in database criteria.

Note:

  • In Java 8 and later, consider using the LocalDateTime class and DateTimeFormatter for more flexible date and time handling.
  • Alternatively, the ThreeTen Backport project provides these features for Java versions prior to 8.

The above is the detailed content of How to Format a Java Calendar Date as yyyy-MM-dd?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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