0

i have this

String prueba = "25 - 2 - 2015";

And lets suppose its

25: Day
2: Month
2015: Year

So i wanna get this

String year = "2015";
String month = "2";
String day  = "25";

The Problem its the "Month" can have more than one character

(example nov has "11" and jan has "1")

and day too ( can we have day "1" or day "25") so in this case substring its imprecise so i need to cut them stopping in the dashes

So how can i cut the prueba String into 3 variables between dashes? Thanks !

Note: Sorry about my english.-

Oku
  • 61
  • 10

4 Answers4

4

Use split method like this:

String prueba = "25 - 2 - 2015";
String[] tokens = prueba.split("\\s*-\\s*");
String day  = tokens[0];
String month = tokens[1];
String year = tokens[2];

*Because of the regex, the split will work with any number of spaces
(For example String prueba = "25- 2 - 2015"; works too)

Thanks guys for pointing it out

Tommaso Bertoni
  • 2,333
  • 1
  • 22
  • 22
  • 4
    It would be a better idea to just split on "-" and then trim the individual tokens. This way it will work for uneven spaces as well.. – Chetan Kinger Mar 03 '15 at 16:53
  • @AbbéRésina I guess you missed the earlier version of this answer. It was only edited after my comment. Click on the edited link and you will understand the context of my comment. – Chetan Kinger Mar 04 '15 at 10:16
  • yes @bot, thanks for pointing it out... but as you can see, i modified my answer so now it works – Tommaso Bertoni Mar 04 '15 at 10:17
  • @TommyTopas Yes it works. I am pointing out to Abbe that he missed the edit which makes his comment pointless.. – Chetan Kinger Mar 04 '15 at 10:18
1

You could do

String[] array = prueba.split("\\D+");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

You have 2 methods:

String myDate = "25 - 2 - 2015";

Either by splitting the String and getting the different substrings.

String[] comp = myDate.split("\\s*-\\s*");
int day = Integer.parseInt(comp[0]); 
int month = Integer.parseInt(comp[1]);
int year = Integer.parseInt(comp[2]);

Or by parsing the formatted date

SimpleDateFormat form = new SimpleDateFormat("dd - MM - yyyy");
Date date = form.parse(myDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR); 
T.Gounelle
  • 5,953
  • 1
  • 22
  • 32
0

this should work

String prueba = "25 - 2 - 2015";
    String[] split = prueba.split("-");
    String day = split[0].trim();
    String month = split[1].trim();
    String year = split[2].trim();
    System.out.println(day + " " + month + " " + year);
pL4Gu33
  • 2,045
  • 16
  • 38