-3

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];
user2628615
  • 13
  • 3
  • 10

3 Answers3

2

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.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

The way you went with is not the right way. It would be way better to convert the digits string into Date object and then use the print format to print it as you like.

This answer can help you

Community
  • 1
  • 1
nheimann1
  • 2,348
  • 2
  • 21
  • 33
0
String date = "01062014";
DateFormat ft = new SimpleDateFormat("MMddyyyy");
DateFormat ft1 = new SimpleDateFormat("MMMM dd, yyyy");


System.out.println(ft1.format((Date)ft.parse(date)));
sasankad
  • 3,543
  • 3
  • 24
  • 31
  • 1
    `("ddMMyyyy")` supposed to be `("MMddyyyy")` because in `"01062014"`, `01` is month – Baby Jan 07 '14 at 01:22
  • @RafaEl, Thanks for pointing that out. I just read the numerical value without looking at OP dateformat. my bad – sasankad Jan 07 '14 at 02:22