Like the others I am assuming that cc
is for century. So ccyy
is the same as yyyy
. Formatters for other languages than Java exist that accept cc
or CC
for century.
Edit: no conversion necessary
Since ccyy
means yyyy
, there is no conversion to do from yyyyMMdd
to ccyyMMdd
. The string you already got in yyyyMMdd
format is also the string that you want.
Original answer
Originally you had asked for a conversion from yyMMdd
to ccyyMMdd
. For example, todays’s date would be converted from 190415
to 20190415
.
To make that conversion correctly you need to know which century is intended. If the date is for a concert ticket to be sold, you can probably safely assume that the year is within the next 20 years (including current year). If it’s a birthday of a living person, you’re already screwed, sorry, because it might be in the last 110 years or more, so you cannot know whether 150415
means year 1915 or 2015, century 19 or 20. In any case, I recommend that you decide on a range of acceptable dates, best somewhat narrower than 100 years so that you have some validation and a chance to detect if some day a date violates your assumptions.
java.time
For the sake of the example let’s assume the date is within the last 30 or the coming 5 years (this allows us to obtain century 19 or 20 depending on the year).
// The base year just needs to be before the minimum year
// and at most 99 years before the maximum year
int baseYear = Year.now().minusYears(40).getValue();
DateTimeFormatter originalDateFormatter = new DateTimeFormatterBuilder()
.appendValueReduced(ChronoField.YEAR, 2, 2, baseYear)
.appendPattern("MMdd")
.toFormatter();
String originalDateString = "921126";
LocalDate today = LocalDate.now(ZoneId.of("Africa/Bangui"));
LocalDate date = LocalDate.parse(originalDateString, originalDateFormatter);
if (date.isBefore(today.minusYears(30)) || date.isAfter(today.plusYears(5))) {
System.out.println("Date " + originalDateString + " is out of range");
} else {
String ccyymmddDateString = date.format(DateTimeFormatter.BASIC_ISO_DATE);
System.out.println("String " + originalDateString + " was reformatted to " + ccyymmddDateString);
}
Output when running today is:
String 921126 was reformatted to 19921126
Some other original strings yield:
String 200430 was reformatted to 20200430
Date 240430 is out of range
The format you want, yyyyMMdd
, agrees with the built-in BASIC_ISO_DATE
format, so I just use that to format the date.
I recommend you don’t use SimpleDateFormat
. That class is notoriously troublesome and fortunately long outdated. Also SimpleDateFormat
doesn’t let you control the interpretation of a 2-digit year the way I do above. Instead I am using DateTimeFormatter
and other classes from java.time, the modern Java date and time API.
Link: Oracle tutorial: Date Time explaining how to use java.time.