Home >Java >javaTutorial >How Can I Convert a Java Calendar Date to yyyy-MM-dd Format?
Problem:
Converting a Calendar date to the commonly used yyyy-MM-dd format is essential for various applications, including data validation and database operations. However, the default Java Date object does not provide a direct method to obtain this format.
Solution:
To achieve this conversion, one can leverage the formatting capabilities of Java. Here are two approaches:
1. Using SimpleDateFormat (Java 7 and earlier):
Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); String date1 = format1.format(cal.getTime());
This solution utilizes SimpleDateFormat to parse and format the Date object into the desired format.
2. Using LocalDateTime (Java 8 and later):
LocalDateTime ldt = LocalDateTime.now().plusDays(1); DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); String formatter = format1.format(ldt);
With Java 8 and later, LocalDateTime provides an alternative method for date manipulation. DateTimeFormatter can be used to format the date into the required format.
Note:
The above is the detailed content of How Can I Convert a Java Calendar Date to yyyy-MM-dd Format?. For more information, please follow other related articles on the PHP Chinese website!