2012-11-27 75 views
0

我得到一個返回的解析JSON結果,字符串值的日期形式如「27-11-2012」,我解析爲日期對象。我對這個代碼是:只解析DateFormat中的年份Java

public Date stringToDateReport(String s){ 
     //Log.d(TAG, "StringToDateReport here is " + s); 
     DateFormat format; 
     Date date = null; 

     //if(s.matches("")) 
     format = new SimpleDateFormat("dd-MMM-yyyy"); 

     try { 

      date = (Date)format.parse(s); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 
     return date; 
    } 

現在,功能已經實現了我的問題,有時JSON只返回了一年的物體,像「2012」,並給了我一個「ParseException的:無法解析日期」的預期。我正在考慮使用正則表達式匹配字符串模式並從那裏解析,但不知道如何做到這一點。任何想法,無論如何只解析一個DateFormat年?

+2

'格式=新的SimpleDateFormat( 「YYYY」);' – Houcine

+1

@Houcine的問題是,有時一個完整的字符串被髮送,其他時間,就在一年... – ppeterka

+0

@sparrow看到我的回答:) – Houcine

回答

1

我想嘗試:

public Date stringToDateReport(String s){ 
    DateFormat format; 
    Date date = null; 

    format = new SimpleDateFormat("dd-MM-yyyy"); 

    if(s.length()==4) { 
     format = new SimpleDateFormat("yyyy"); 
    } 
    try { 
     date = (Date)format.parse(s); 
    } catch (ParseException e) { 
     //you should do a real logging here 
     e.printStackTrace(); 
    } 
    return date; 
} 

背後的邏輯是,以檢查串只有4長,然後應用不同的格式。在這種情況下,這種簡單的方法就足夠了,但在其他方法中,可能需要使用正則表達式。

+0

謝謝!應該真的想到了。再次感謝! – irobotxxx

2

試試這個代碼

public Date stringToDateReport(String s){ 
    //Log.d(TAG, "StringToDateReport here is " + s); 
    DateFormat format; 
    Date date = null; 

    if(s.indexOf("-") < 0){ 
    format = new SimpleDateFormat("yyyy"); 
    }else{ 
    format = new SimpleDateFormat("dd-MMM-yyyy"); 
    } 
    try { 

     date = (Date)format.parse(s); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    return date; 
} 

是否有可能在具有在String s另一種格式?或者只是這兩個?

+1

你的意思是's.indexOf(「 - 」)<0'?如果沒有「 - 」,它應該是-1。 – thedan

+0

謝謝!我的錯! –

+0

@RenatoLochetti謝謝!抱歉只能接受一個答案。 – irobotxxx

0
public Date stringToDateReport(String strDate){ 
    DateFormat formatnew SimpleDateFormat("dd-MM-yyyy"); 
    Date date = null; 

    if(strDate.length()==4) { 
     format = new SimpleDateFormat("yyyy"); 
    } 
    try { 
     date = (Date)format.parse(strDate); 
    } catch (ParseException e) { 
     //error parsing date 
     e.printStackTrace(); 
    } 
    return date; 
} 

然後調用它像這樣:

String strDate = yourJson.getString("date"); 
Date d = stringToDateReport(strDate); 
相關問題