2012-03-12 99 views

回答

0

一個可行的解決方案...對此,一個相當嚴格的正則表達式就像你看到的那樣相當冗長。

String input = "29-NOV-11 06.05.41.831000000 AM"; 

input = input 
     .replaceFirst(
       "(\\d+-\\w+-\\d+\\s\\d+\\.\\d+\\.\\d+\\.\\d{3})\\d{6}(\\s(\\w+))", 
       "$1$2"); 
try { 
    SimpleDateFormat sdf = new SimpleDateFormat(
      "dd-MMM-yy HH.mm.ss.SSS aa"); 

    Date date = sdf.parse(input); 
    System.out.println(sdf.format(date)); 

} catch (ParseException e) { 
    e.printStackTrace(); 
} 

你可以使用substr如果字符串總是固定的寬度,你認爲正則表達式有點矯枉過正。

input = input.substring(0, 22) + input.substring(28, 31); 
0

如果時間戳由字符串表示,您可以使用正則表達式來解析出額外的零。

+0

你必須小心不要移動太多數字。例如41.831是41秒和831毫秒,但41.83是42秒,83毫秒和41.8分析爲41秒和8毫秒。 – 2012-03-12 09:19:04

+0

我不知道,謝謝。看起來很瘋狂,但沒關係! – chooban 2012-03-12 09:32:20

+0

Yeh ..its string ...問題是那些尾隨零...如何使用正則表達式將它們轉換爲mill + micro或微秒?我需要這些毫秒(並且也是尾隨AM/PM) – 2012-03-12 09:35:32

2

額外的數字是納秒。您不能將這些包含在SimpleDateFormat或標準庫中。在你的情況下最簡單的事情就是在解析日期/時間之前刪除它們。