0

I have a string date in format (dd-MMM-yyyy) like (23-SEP-2019). I want to seperate day month and year from above string in integer like day = 23, month = 09, year = 2019.

halfer
  • 19,824
  • 17
  • 99
  • 186

3 Answers3

0
String pattern = "dd-MMM-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = simpelDateFormat.parse(yourdateString);
Calendar now = Calendar.getInstance();
now.setTime(date);
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
Qingfei Yuan
  • 1,196
  • 1
  • 8
  • 12
0

There's a few ways to do this, but I would go with this:

//convert it to a char array.
char[] asChars = dateString.toCharArray();
//Parse the date and year and from new strings.
int dayVal = Interger.ParseInt(""+asChars[0]+asChars[1]);
int yearVal = Interger.ParseInt(""+asChars[7]+asChars[8]+asChars[9]+asChars[10]);
//use a switch for the month.
int monthVal = 0;
String monthString = ""+asChars[3]+asChars[5]+asChars[6];
switch (monthString) {
    case "JAN" :
        monthVal = 1;
        break;
    case "FEB" :
        monthVal = 2;
        break;
    case "MAR"  :
        monthVal = 3;
        break;
    case "APR" :
        monthVal = 4;
        break;
    case "MAY" :
        monthVal = 5;
        break;
    case "JUN" :
        monthVal = 6;
        break;
    case "JUL" :
        monthVal = 7;
        break;
    case "AUG" :
        monthVal = 8;
        break;
    case "SEP" :
        monthVal = 9;
        break;
    case "OCT" :
        monthVal = 10;
        break;
    case "NOV" :
        monthVal = 11;
        break;
    case "DEC" :
        monthVal = 12;
        break;
}

You'll need to put that in a try block and you'll want a catch for NumberFormatException and IndexOutOfBounds, in both cases the string was formatted incorrectly.

You will also separately need to check that the month string matched a month, so either add a default case to the switch or have a check that monthVal>0 after all that.

If you really want to be sure the original string was formatted correctly (which is a separate issue but I think still relevant) then you could check the string is of length 11 before all of that.

CasualViking
  • 262
  • 1
  • 9
0

You can use java 8 LocalDate feature. I provide below the code, you can check.

String dateStr = "23-Sep-2019";
    DateTimeFormatter formatter_1 = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
    LocalDate localDate = LocalDate.parse(dateStr, formatter_1);
    System.out.println("localDate_1 = " + localDate);
    int day = localDate.getDayOfMonth();
    int month = localDate.getMonthValue();
    int year = localDate.getYear();
    System.out.println(day + "-" + month + "-" + year);
Sambit
  • 7,625
  • 7
  • 34
  • 65