2015-10-07 102 views
1

我從字符串格式的JSON響應中獲取日期,但現在我想將該日期轉換爲日期格式。我如何將這個strActiondate:= 9/28/2015 6:52:41 PM轉換成日期,以便我可以插入Sq-lite數據庫。Android將字符串轉換爲日期

我已經嘗試這樣

strActiondate = jobjVessels.getString("actionDate");     

Log.e("strActiondate ", " = " + strActiondate); 
try{ 
    DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); 
    Date netDate = (new Date(Long.parseLong(strActiondate))); 
    Log.e("netDate "," = "+netDate); 

} 
catch(Exception ex){ 
    ex.printStackTrace(); 
} 

我想在相同的格式日期= 9/28/2015 6:52:41 PM

回答

0

使用此代碼

strActiondate = jobjVessels.getString("actionDate"); 

Log.e("strActiondate ", " = " + strActiondate); 
try{ 
    DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a"); 
    Date netDate = sdf.parse(strActiondate); 
    Log.e("netDate "," = "+netDate); 
} 
catch(Exception ex){ 
    ex.printStackTrace(); 
} 
1

DateFormatMM/dd/yyyy,是不適用於此日期: 9/28/2015 6:52:41 PM

你需要這個字符串相匹配的良好SimpleDateFormat

a Am/pm marker  Text PM 
H Hour in day (0-23) Number 0 
m Minute in hour  Number 30 
s Second in minute Number 55 

所以這個:

String strActiondate = "9/28/2015 6:52:41 PM"; 
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a"); 
Date netDate = sdf.parse(strActiondate); 
System.out.println(netDate); 

將輸出:

Mon Sep 28 06:52:41 CEST 2015 

在您的代碼:

try{ 
    DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a"); 
    Date netDate = sdf.parse(strActiondate);  
    Log.d("netDate "," = "+netDate); // log.e is an error... so better d or i 
}