2016-10-04 86 views
0

所以我想要做的是基本上,我有一個字符串變量,我試圖將該字符串轉換爲時間格式,以便我可以然後利用這段時間爲當天創建一個警報。安卓 - 字符串到時間(只)使用簡單的日期格式

例如。

字符串stringTime =「1:05 PM」

,我想將其轉換成這樣一個報警將被設置在下1:05 PM熄滅日期格式。

當我嘗試使用SimpleDateFormat時,它顯示爲日期和時間,並且日期回到1970年。請參閱下面的代碼。

Date[] date_formatted_times_A; 
SimpleDateFormat formatter = new SimpleDateFormat("h:m a"); 

public Date[] DateConverterA (String[] times_A){ 

      date_formatted_times_A = new Date[times_A.length]; 

      for(int i=0;i<times_A.length;i++) 
      { 
       try { 
        date_formatted_times_A[i] = formatter.parse(times_A[i]); 



       } catch (java.text.ParseException e) { 
        e.printStackTrace(); 
       } 
      } 
      return date_formatted_times_A; 

} 

但結果我從這個得到的,在案件的串時間爲1:05 PM是「週四1月1 13:05:00 GMT 1970年」。我完全失去了我應該如何着手。請記住,我只想要時間,我需要它的方式,然後我可以用它來設置鬧鐘。時間將存儲在DATE數組中(或者您認爲更合適的數組)。 24小時或12小時是好的!

+0

我敢肯定你根本沒有在互聯網或這個SO網絡上搜索。有數百萬這樣的問題。請問之前,請搜索! –

+0

我確實搜索過。但我不明白他們。因此,我問我的原因,我可以得到一個具體的答案。 – Razoe

回答

0

你簡單的日期格式應該是:
SimpleDateFormat formatter = new SimpleDateFormat(hh:mm a");

請嘗試以下和自己學習不同的格式:

try { 
    SimpleDateFormat format = new SimpleDateFormat("hh:mm a"); //if 24 hour format 
    // or 
    SimpleDateFormat format = new SimpleDateFormat("HH:mm"); // 12 hour format 
    java.util.Date d1 =(java.util.Date)format.parse(your_Time); 
    java.sql.Time ppstime = new java.sql.Time(d1.getTime()); 
} catch(Exception e) { 
    Log.e("Exception is ", e.toString()); 
} 
+1

非常感謝。 – Razoe

0

丟棄的日期部分,並通過GregorianCalendar只使用時間字段(避免棄用警告)。

GregorianCalendar timepoint=new GregorianCalendar(); 
timepoint.setTime(date); // date obtained by parsing 
int hours=timepoint.get(Calendar.HOUR_OF_DAY); 
int minutes=timepoint.get(Calendar.MINUTE); 
int seconds=timepoint.get(Calendar.SECOND);