2016-03-01 75 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