To format a date from the "ddmmmyyyy" format to the "ddmmyy" format in Java, you can use the DateTimeFormatter
class from the java.time
package.
Here's an example of how to format a date from the "ddmmmyyyy" format to the "ddmmyy" format in Java:
// Parse the input date string using the "ddMMMyyyy" format DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("ddMMMyyyy"); LocalDate date = LocalDate.parse("22Dec2021", inputFormatter); // Create a DateTimeFormatter object with the desired output format DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("ddMMyy"); // Use the format() method of the DateTimeFormatter to format the LocalDate object String formattedDate = date.format(outputFormatter); System.out.println("The formatted date is " + formattedDate);
In the above example, the input date string is first parsed using the parse()
method of the LocalDate
class and the "ddMMMyyyy" format. The resulting LocalDate
object is then stored in a variable called date
.
Next, a DateTimeFormatter
object is created with the desired output format, using the ofPattern()
method and a format string. The format string specifies that the day should be shown with 2 digits, the month with 2 digits, and the year with 2 digits.
The format()
method of the DateTimeFormatter
is then used to format the LocalDate
object and store the result in a String
variable called formattedDate
. Finally, the formatted date is printed to the console.
The output of this example will be "The formatted date is 22Dec21".
Note that the java.time
package was introduced in Java 8 and replaces the older java.util.Date
and java.text.SimpleDateFormat
classes. If you are using an older version of Java, you can use the SimpleDateFormat
class to format a Date
object in a similar way.