java

Convert from MMDDYYYY to date java


I have a string that is in the format of MMDDYYYY (ex. 01062014) and I wish to convert it to something like January 6, 2014. The code I currently have does not work and returns the default month (Something has gone wrong) and then 10, 6204.

String[] datesRaw = args[3].split("");
String[] dates = { datesRaw[0] + datesRaw[1], datesRaw[2] + datesRaw[3], datesRaw[4] + datesRaw[5] + datesRaw[6] + datesRaw[7] };
int[] numbers = new int[dates.length];
for (int i = 0; i < dates.length; i++) {
    numbers[i] = Integer.parseInt(dates[i]);
}
String month = "Something whent wrong";
switch (numbers[0]) {
    case 1:
        month = "January";
        break;
    case 2:
        month = "February";
        break;
    case 3:
        month = "March";
        break;
    case 4:
        month = "April";
        break;
    case 5:
        month = "May";
        break;
    case 6:
        month = "June";
        break;
    case 7:
        month = "July";
        break;
    case 8:
        month = "August";
        break;
    case 9:
        month = "September";
        break;
    case 10:
        month = "October";
        break;
    case 11:
        month = "November";
        break;
    case 12:
        month = "December";
        break;
}
fileName = month + " " + dates[1] + ", " + dates[2];

Solution

  • Use two SimpleDateFormat objects - one to parse the initial String into a Date, and the other to format the resulting Date into a String.

    public String convert(String inputString) {
        SimpleDateFormat inputFormat = new SimpleDateFormat("MMddyyyy");
        SimpleDateFormat outputFormat = new SimpleDateFormat("MMMM d, yyyy");
        Date theDate = inputFormat.parse(inputString);
        return outputFormat.format(theDate);
    }
    

    You would probably want to create those two SimpleDateFormat objects as constants inside the class that has this method, but be aware that such an approach would make this method not thread safe.