Take the tour ×

This question already has an answer here:

The title is quite difficult to understand, please forgive me, thanks.

Assume that I have a string like this : 1/1/2013 or 11/1/2013 or 11/12/2013 which represent the date.

and what I want is only the string in the middle of /**/ which mean the month.

I'm not try anything yet, because I have no idea to get a string in the middle of another string.

Could someone give me any idea or if you used to solve this kind of problem please share the solution, thanks in advance.

share|improve this question
Have you tried str.subSequence(begin, end)? –  Emracool Jan 4 at 6:52
IMO, its better if you parse it as a Date object and then access its month property. You can later use that object as well –  Habib Jan 4 at 6:56
I think it's not really good for my case, because position of "/" is not in the fix position. –  Edward Sullen Jan 4 at 6:57
add comment

marked as duplicate by Raedwald, chollida, TryTryAgain, Jeremy J Starcher, madth3 Jun 12 at 4:33


6 Answers

Just use split() to split on /, and take the second value:

String date = "1/12/2013";
String month = date.split("/")[1];
share|improve this answer
omg, work as heaven... thanks you so much :) i'm alive again. –  Edward Sullen Jan 4 at 6:58
@EdwardSullen: You're welcome. :) –  Keppil Jan 4 at 7:03
add comment
SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
System.out.println(dateFormat.format(new SimpleDateFormat("dd/MM/yyyy").
share|improve this answer
add comment

The other answers have covered most good answers. One other approach which might be over kill is regular expressions

 Pattern p = Pattern.compile("/.*/");
 Matcher m = p.matcher("1/1/2013");
 String month = m.group();
share|improve this answer
add comment
String date = "11/12/20113";
String month = date.substring(date.indexOf("/")+1, date.lastIndexOf("/")) 

here we are passing the index of the first "/" and the index of second "/" as parameters to substring(), which will return the string in between "/" and "/" just as you asked!

share|improve this answer
add comment


    String s = "1/12/2013";
    String m = s.substring(s.indexOf('/') + 1, s.lastIndexOf('/'));

note that this is much more efficient than splitting, parsing or regex. No one extra object is created, even String.substring is special, it shares inner char buffer without copying.

share|improve this answer
add comment

You can split the string by the / character into an array like this:

String[] dateArray = date.split ("/");

The month is then the second element:

String month = dateArray[1];
share|improve this answer
add comment
