Like split line in java

I have a project in android and I need a split line, actually the date here is the line I'm going to split:

String datetime = "01/03/2013 09:00"; 

and so I call them:

 int year = splitDateTime(dateTime)[0]; 
 public int[] splitDateTime(String datetime){ String date_time = datetime; String delimiter = "//:"; String[] sParts; int[] intParts; sParts = date_time.split(delimiter); intParts = new int[sParts.length]; for(int i =0; i < sParts.length ; i++) intParts[i] = Integer.parseInt(sParts[i]); return intParts; } 

but he continues to give me a mistake, so I would be glad if you help me out of the guys. greetings

+4
source share
4 answers

I'm sure you mean something like:

 String datetime = "01/03/2013 09:00"; String[] sParts = datetime.split("[/:\\s+]"); int[] iParts = new int[sParts.length]; for(int i = 0; i < sParts.length; i++) iParts[i] = Integer.parseInt(sParts[i]); System.out.println(Arrays.toString(iParts)); 

OUTPUT:

 [1, 3, 2013, 9, 0] 
+5
source

I think you should use Calendar

 String dateTime = "01/03/2013 09:00"; SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy HH:mm"); Date d = f.parse(dateTime); Calendar c = Calendar.getInstance(); c.setTime(d); int year = c.get(Calendar.YEAR); 
+3
source

You can use the regex using something like ^(\d+)/(\d+)/(\d+) (\d+):(\d) , and you can get each captured group.

0
source

I think StringTokenizer-based solution will be the fastest

 public static int[] splitDateTime(String dateTime) { int[] intParts = new int[5]; StringTokenizer t = new StringTokenizer(dateTime, "/ :"); for (int i = 0; t.hasMoreTokens(); i++) { intParts[i] = Integer.parseInt(t.nextToken()); } return intParts; } public static void main(final String[] args) throws IOException { System.out.println(Arrays.toString(splitDateTime("01/03/2013 09:00"))); } 

Output

 [1, 3, 2013, 9, 0] 
0
source

All Articles