I there a way to format dates which contain century in it to common format. Format date in cyymmdd to MM/dd/yyyy.
Example,
Convert 1140711 to o7/11/2014
I there a way to format dates which contain century in it to common format. Format date in cyymmdd to MM/dd/yyyy.
Example,
Convert 1140711 to o7/11/2014
If you are talking about converting a String in format:
1140711
to
07/11/2014
DateFormat df1 = new SimpleDateFormat("yyddMM");
DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
String dateString = "1140711";
System.out.println(df2.format(df1.parse(dateString.substring(1, dateString.length()))));
As far as I know the only date-time-library which is capable of processing century fields is Joda-Time.
LocalDate date = DateTimeFormat.forPattern("CyyMMdd").parseLocalDate("1140711");
System.out.println("Century=" + date.getCenturyOfEra()); // 20
String usFormat = DateTimeFormat.forPattern("MM/dd/yyyy").print(date);
System.out.println(usFormat); // output: 07/11/2014
As you can see the input digit "1" for century is simply ignored because Joda-Time only evaluates the other fields to a valid date. Personally I would reject such a century input because we are in 21th of century with the century number 20, not 1. So Joda-Time has its limits here, but are you really sure that you have a century of 1 in your input, or is it just a typo?
I had to do the opposite thing, convert date to cyyMMdd.
String centuryCharacterOfDateFormat(LocalDate valueDate) {
int year = valueDate.getYear();
int yearMinus1900 = year - 1900;
if (yearMinus1900 < 0) {
throw new PipRuntimeException("Invalid value date, because it is before 1900. " + valueDate);
} else if (yearMinus1900 < 100) {
return "0";
} else {
String strVal = String.valueOf(yearMinus1900);
char hundredthChar = strVal.charAt(strVal.length() - 3);
return String.valueOf(hundredthChar);
}
}
You could use the similar logic to do the opposite conversion. To get year, you could add 1900 and hundreds of the first character.
In below method in example date string follow the century date format "CYYMMDD" where C for century, YY for year, MM for month and DD for day. Century values aredescribe below: if Century value is 0 then it will represent 20th century, years b/w 1900 to 1999. if Century value is 1 then it will represent 21st century, years b/w 2000 to 2999.
public LocalDate convertedDate () {
String dateString = "1230124";
int century = Integer.parseInt(dateString.substring(0, 1));
int year = Integer.parseInt(dateString.substring(1, 3));
int month = Integer.parseInt(dateString.substring(3, 5));
int day = Integer.parseInt(dateString.substring(5, 7));
LocalDate ld= LocalDate.of((century + 19) * 100 + year, month, day);
System.out.printl**strong text**n("Converted Date : "+ld);
return ld;
}