我想用毫秒分割日期並以我的格式打印,但索引超出了界限異常。它在分割(「/」)的情況下工作,但不與分割(「。」)一起工作。字符串拆分功能不能按要求工作
我不知道爲什麼會發生這種情況。
代碼是:
public class c {
public static void main(String[] arg)
{
Date date=new Date();
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.FFF");
System.out.println(formatter.format(date));
String a=formatter.format(date);
String b[]=a.split(" ")[0].split("/");
String x1=(Integer.parseInt(b[2])-2000)+b[1]+b[0];
System.out.println("date part is : "+x1);
String c[]=a.split(" ")[1].split(":");
System.out.println(c[0]);
System.out.println(c[1]);
System.out.println(c[2]);
System.out.println(c[2].trim().split(".")[0]);// exception at this line
System.out.println(c[2].trim().split(".")[1]);
String x2=c[0]+c[1]+c[2].split(".")[0]+c[2].split(".")[1]+"";
System.out.println("time part is : "+x2);
}
}
日誌是:
08/10/2013 12:02:18.002
date part is : 131008
12
02
18.002
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:0 at c.main(c.java:22)
as @Tichodroma指出,將''。''改爲'「\\。」應該可以做到,但是... ......你的代碼太糟糕了!爲什麼你甚至不打擾所有的連接和拆分變形,而在'Date'類中可以使用非常簡單的訪問器? –
@Orabîg「日期」上的訪問器都已棄用。 – 2013-10-08 06:59:42
嗯,好吧,但使用SimpleDatFormat並從結果字符串中提取信息..這聽起來比使用基本數據訪問器更好嗎?我不這麼認爲(imho) –