Converting Calendar Dates to yyyy-MM-dd Format in Java
When working with dates in Java, it's often necessary to convert them into a specific format for data processing, comparisons, or storage. One common format is the "yyyy-MM-dd" format, widely used in databases and other systems. This format represents dates as a string with the year, month, and day components separated by hyphens.
To convert a Calendar object to the yyyy-MM-dd format, you can use the SimpleDateFormat class. Here's an example:
Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); String date1 = format1.format(cal.getTime());
The format1 variable represents a date format with the specified pattern. The format() method takes the date represented by the Calendar object, cal.getTime(), and formats it into the desired string representation. In this case, it will produce a string in the yyyy-MM-dd format.
However, it's important to note that the converted string represents the same date, not a different date. The Calendar object contains the actual date information, while the formatted string is just a representation. This distinction is important for maintaining data integrity and avoiding confusion in date operations.
The above is the detailed content of How to Convert Java Calendar Dates to yyyy-MM-dd Format?. For more information, please follow other related articles on the PHP Chinese website!