i have project in android, and i need split string, which is actually date here is the String that i'm going to split:
String datetime = "01/03/2013 09:00";
and this is how 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 it keeps giving me an error, so i would be happy if you help me out guys. cheers
I bet 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]
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);
您可以使用正则表达式,使用类似^(\\d+)/(\\d+)/(\\d+) (\\d+):(\\d)
,您可以获取每个捕获的组。
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.