Home >Java >javaTutorial >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:
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!