2016-03-01 102 views
1

我有一個Android應用程序,並且我只在Android M中面對來自Android的CalendarView的getDate()方法的問題。我已經在6.0中對它進行了測試 - 它的工作原理類似於一個魅力。Android getDate返回錯誤的日期

問題是:當用戶在我的日曆中選擇日期時,它僅返回今天。

這是我的代碼:

CalendarView calendarView = (CalendarView) findViewById(R.id.input_commitmentAdd_date); 
commitmentItem.date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(calendarView.getDate())); 

我的日曆視圖:

<CalendarView 
    android:id="@+id/input_commitmentAdd_date" 
    android:layout_width="match_parent" 
    android:layout_height="300dp" 
    android:layout_marginLeft="@dimen/form_margin" 
    android:layout_marginRight="@dimen/form_margin" 
    android:layout_marginTop="@dimen/form_spacing" /> 

謝謝你,夥計們!

回答

3

我已經想通了。爲了解決這個問題,我只是改變了它:

CalendarView calendarView=(CalendarView)findViewById(R.id.input_commitmentAdd_date); 
commitmentItem.date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(calendarView.getDate())); 

要:

calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() { 

     @Override 
     public void onSelectedDayChange(CalendarView view, int year, int month, 
             int dayOfMonth) { 
      int correctMonth = month + 1; 
      date = String.valueOf(year + "-" + correctMonth + "-" + dayOfMonth); 
     } 
    }); 
+1

感謝您分享您的答案。我開始拉我的頭髮。 (只是爲什麼getDate()不能像它在文檔中寫的那樣工作......只返回今天的日期......完全不合邏輯的東西) –

+0

這開始發生在我身上的牛軋糖。令人沮喪的 –

-1
Calendarview cv=findviewbyid(R.id.cv); 
    long selectedDateInMillis; 
    long current = cv.getDate(); 
    if(current!=new Date().getTime()) 
    { 
     selectedDateInMillis=new Date().getTime(); 
    } 
+1

請解釋這個解決方案是如何工作的,它與原始海報(OP)的解決方案有什麼不同,以及後者中錯誤的本質是什麼。 –

+0

此解決方案適用於您希望日曆視圖和caledarview中的日期/時間以毫秒爲單位給出錯誤日期的情況。 – Alpha