2015-05-05 48 views
0
Input : 2007-02-09 00:00:00.0 

Expected : 2007-02-09 

如何使用Java正則表達式截斷00:00:00.0Java正則表達式截斷時間戳值

+1

1)你不需要爲正則表達式。 2)你有什麼嘗試? – Seelenvirtuose

+0

爲什麼你想使用正則表達式。使用'SimpleDateFormat' – Jens

+0

嘗試使用正則表達式來截斷空格後的字符,但我沒有得到我的預期 – Prabu

回答

2

你可以做

String a="2007-02-09 00:00:00.0"; 
String b=a.split("\\s")[0]; 
System.out.println(b);   // 2007-02-09 

Demo

您還可以使用SimpleDateForMat

String a = "2007-02-09 00:00:00.0"; 
Date myDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(a); 
System.out.println(myDate); 
String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(myDate); 
System.out.println(formattedDate);  // 2007-02-09 

Demo

+0

謝謝,當我們嘗試產生一個NullPointerException字符串publicationDate1 = portfolioDetails.get(4); \t \t String publicationDate = publicationDate1.split(「\\ s」)[0]; \t \t assetPortfolio.put(「publicationdate」,publicationDate); – Prabu

+0

@Prabu打印並檢查'publicationDate1'的值我認爲它的'null' – silentprogrammer

+0

是的,它是空的,謝謝 – Prabu

0

提示:

  1. 使用indexOf([space])substring(index+1)方法(不需要正則表達式)。

如果您在使用正則表達式彎曲:

  • String#replaceAll() - >捕捉一切,直到空間,然後替換爲拍攝組的一切。
  • 0

    試試這個:

    String s = "2007-02-09 00:00:00.0"; 
    System.out.println(s.replaceAll("\\s\\d{2}:\\d{2}:\\d{2}\\.\\d*", "")); 
    

    這將替換什麼也沒有timepart,讓您得到預期的結果。