Home >Java >javaTutorial >How Can I Convert a Calendar Date to yyyy-MM-dd Format in Java?
When working with dates in Java, it's often necessary to convert them to a particular format for display or database comparison. One commonly encountered format is yyyy-MM-dd.
Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); Date date = cal.getTime(); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
This code snippet initializes a calendar and adds one day to the current date. The resulting Date object is then formatted using a SimpleDateFormat in the desired format. However, the resulting string will include additional information such as the time.
To obtain a Date object in yyyy-MM-dd format, you can follow these steps:
Java 8 introduces the LocalDateTime class and the DateTimeFormatter interface for more flexible date and time handling.
LocalDateTime ldt = LocalDateTime.now().plusDays(1); DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH); String formatted = formmat1.format(ldt);
For Java versions prior to 8, you can use the ThreeTen Backport library to access modern date and time APIs.
Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); String formatted = format1.format(cal.getTime());
This will result in a String in the required format. You can parse this string back to a Date object using the parse() method of the SimpleDateFormat class if necessary.
It's important to note that while the Date objects created in the above examples are displayed differently, they represent the same date. The formatting simply changes the way the date is presented.
The above is the detailed content of How Can I Convert a Calendar Date to yyyy-MM-dd Format in Java?. For more information, please follow other related articles on the PHP Chinese website!