2015-10-04 24 views
0

我在m android應用中使用了CalendarPickerview,它可以幫助我選擇多個日期。我得到arraylist<>中的選定日期。問題是我以格式[Sun Oct 04 00:00:00 GMT+05:30 2015]獲取日期。 但我應該以格式04/10/2015獲得日期。我該如何達到相同的效果。 在此先感謝。 下面給出的是我使用的示例代碼。從android中的數組列表中解析僅日期

calendar=(CalendarPickerView) rootView2.findViewById(R.id.calendar_view); 
    Date today=new Date(); 
    calendar.init(today,nextYear.getTime()).withSelectedDate(today).inMode(CalendarPickerView.SelectionMode.MULTIPLE); 
    // calendar.highlightDates(getHolidays()); 
    String[] items1 = new String[]{"Select Something"}; 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, items1); 
    button= (Button) rootView2.findViewById(R.id.action_next); 
    datesSelected = (TextView) rootView2.findViewById(R.id.dateView); 
    button.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      ArrayList<Date>selectedDates=(ArrayList<Date>)calendar 
        .getSelectedDates(); 
      Toast.makeText(getActivity(), selectedDates.toString(), 
        Toast.LENGTH_LONG).show(); 
      SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); 
      String dates=selectedDates.toString(); 
      datesSelected.setText(dates); 

回答

0

可以使用的SimpleDateFormat至今轉換成所需的格式,如:

public static String getFormatedDate(String strDate, String sourceFormate, 
     String destinyFormate) { 
    SimpleDateFormat df; 
    df = new SimpleDateFormat(sourceFormate); 
    Date date = null; 
    try { 
     date = df.parse(strDate); 

    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 

    df = new SimpleDateFormat(destinyFormate); 
    return df.format(date); 

} 

其中,strDate是日期,sourceFormate是當前的日期格式,destinyFormate是需要的日期格式。

呼叫getFormatedDate喜歡:

getFormatedDate(strDate, 
      "yyyy-MM-dd HH:mm:ss", 
      "mm/dd/yyyy"); 

希望,它可以幫助你。

+0

謝謝你的幫助Rahul。但是我在getFormatedDate(strDate, 「yyyy-MM-dd HH:mm:ss」, 「mm/dd/yyyy」)時收到空指針異常;並返回df.format(日期); 。 –

+0

因爲「yyyy-MM-dd HH:mm:ss」不是你的日期格式,所以你只能使用空指針。使用您在「strDate」中發送的日期格式。 「[Sun Oct 04 00:00:00 GMT + 05:30 2015]」的日期格式爲「[EEE MMM dd HH:mm:ss zzz yyyy]」。試試這個 –

+0

我試過了。但現在我也得到了相同的空指針異常@函數調用點並返回。 –

0

其實你在這裏得到一個Date對象的列表。

ArrayList<Date>selectedDates=(ArrayList<Date>)calendar.getSelectedDates(); 

你提到的格式正是Logprintln()秀(使用Date.toString()將日期轉換爲字符串)。

您可以使用SimpleDateFormat等將Date對象轉換爲您需要的任何格式。