2012-11-09 46 views
1

我有一個字符串,它將從數據庫中返回日期和時間爲2012-11-09 13:20:17。現在我需要從數據庫字符串中獲取時間,並顯示時間如13:20:17 pm,如果手機時間設置爲24 hour,並且手機時間設置爲12 hour,則應將其顯示爲01:20:17 pm。時間格式可以通過這行代碼表示它的24小時或12小時根據手機時間設置的時間格式更改

String timefrmt = Settings.System.getString(context.getContentResolver(),Settings.System.TIME_12_24); 
SimpleDateFormat timesettingsFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
date="2012-11-09 13:20:17"; 
Date myDate=null; 
try { 
    myDate=timesettingsFormat.parse(date); 
} catch (ParseException e1) { 
    // TODO Auto-generated catch block 
    e1.printStackTrace(); 
} 
if(timefrmt==null){ 
    timefrmt="hh:mm aa"; 
} 
SimpleDateFormat timeFormat=new SimpleDateFormat(timefrmt); 
String time=timeFormat.format(myDate); 

我曾嘗試的示例代碼是否高於但其崩潰而獲得。任何人都可以幫我找到一個辦法。 非常感謝

+0

@ Rosalie..you已經不是貼你的錯誤......也許logcat的可以幫助你 –

回答

2

試試這個

public static String dateFormateNote(String date) 
{ 

    try { 
      DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 
      DateFormat df2 = new SimpleDateFormat("hh:mm:ss"); 
      return df2.format(df1.parse(date)); 
     } 
     catch (ParseException e) { 
      return date; 
     } 
}