2016-01-14 26 views
0

我正在開發一個Android應用程序,在該應用程序中我需要解析日期以獲得時間。當我使用我的下面的代碼時,我正在解析異常。使用SimpleDateFormat解析日期以獲取時間

下面是代碼:

SimpleDateFormat parseFormat = new SimpleDateFormat("dd MM hh:mm:ss yyyy"); 
    SimpleDateFormat printFormat = new SimpleDateFormat("h:mm:ss"); 
    Date date; 
    try { //selectedDateTime = Fri Jan 15 09:30:44 GMT+04:00 2016 
     date = parseFormat.parse(selectedDateTime+""); 
     System.out.println(printFormat.format(date)); 
    } catch (ParseException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

這裏是個例外:

java.text.ParseException:無法解析的日期:「週五1月15日09:30:00 GMT + 04:00 2016" (偏移量爲0)

+2

什麼是準確的分析例外您'接收? –

+2

你到底在做什麼? – OBX

+0

java.text.ParseException:Unparseable date:「Fri Jan 15 09:30:00 GMT + 04:00 2016」(at offset 0)@LudwigS這是我得到的異常。 –

回答

0
SimpleDateFormat parserSDF=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy"); 

你格式化掉,試試這個。

0

更新

try { 
     String dateTest = "Fri Jan 15 09:30:00 GMT+04:00 2016"; 

     SimpleDateFormat formatter = new SimpleDateFormat(
       "EEE MMM dd hh:mm:ss zzz yyyy"); 
     java.util.Date d = (java.util.Date) formatter.parse(dateTest); 
     System.out.println("" + d); 

     SimpleDateFormat print = new SimpleDateFormat("hh:mm:ss"); 
     System.out.println(print.format(d)); 

    } catch (ParseException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

輸出

Fri Jan 15 11:00:00 IST 2016 
11:00:00 

下面的代碼可以幫助您瞭解究竟是如何格式化的日期格式

Calendar calendar = Calendar.getInstance(); 


    System.out.println("Date: \t"+calendar.getTimeInMillis()); 

    String dateAsText_ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(""+calendar.getTimeInMillis()))); 
    Date date = new Date(Long.parseLong(""+calendar.getTimeInMillis())); 
    System.out.println(""+dateAsText_); 

    SimpleDateFormat ft = new SimpleDateFormat ("dd-MMM-yyyy"); 
    System.out.println(""+ft.format(date)); 

    SimpleDateFormat time_ft = new SimpleDateFormat ("hh:mm aa"); 
    System.out.println(""+time_ft.format(date)); 

輸出

語法變化
Date: 1452766759531 
2016-01-14 15:49:19 
14-Jan-2016 
03:49 PM 

enter image description here

0

你的字符串是錯誤的。正確的是:

SimpleDateFormat parseFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); 
SimpleDateFormat printFormat = new SimpleDateFormat("HH:mm:ss"); 
0

我想你的初始日期格式是錯誤的。你能分享selectedDateTime的價值嗎? 我猜它在不同的格式(按您的評論),如週五1月15日9時三十分44秒GMT + 04:00 2016

如果是這樣,請嘗試此代碼

SimpleDateFormat parseFormat = new SimpleDateFormat("E MM dd hh:mm:ss z yyyy"); 
SimpleDateFormat printFormat = new SimpleDateFormat("h:mm:ss"); 
Date date; 
try { //selectedDateTime = Fri Jan 15 09:30:44 GMT+04:00 2016 
    date = parseFormat.parse(selectedDateTime+""); 
    System.out.println(printFormat.format(date)); 
} catch (ParseException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
}