2013-10-08 70 views
1

我想用毫秒分割日期并以我的格式打印,但索引超出了界限异常。它在分割(“/”)的情况下工作,但不与分割(“。”)一起工作。字符串拆分功能不能按要求工作

我不知道为什么会发生这种情况。

代码是:

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) 
+6

as @Tichodroma指出,将''。''改为'“\\。”应该可以做到,但是... ......你的代码太糟糕了!为什么你甚至不打扰所有的连接和拆分变形,而在'Date'类中可以使用非常简单的访问器? –

+0

@Orabîg“日期”上的访问器都已弃用。 – 2013-10-08 06:59:42

+0

嗯,好吧,但使用SimpleDatFormat并从结果字符串中提取信息..这听起来比使用基本数据访问器更好吗?我不这么认为(imho) –

回答

5

java.lang.String.split(String regex)需要一个正则表达式作为参数。

单点.是“任何字符”的正则表达式。所以你在每个角色之后分割你的输入。

逃生点:

split("\\."); 
+0

谢谢,它的工作... – HimanshuR

+0

[接受的答复](http://meta.stackexchange.com/a/5235/218453)如果它帮助。 – Jayamohan

0

可以使用java.util.regex.Pattern.quote( “ ”),为了将用字符串“。”

str.split(java.util.regex.Pattern.quote(“。”));

0

尽量不要分裂...你可以随时使用这个formatter.day | .month |小时左右......