2014-09-23 108 views
0

我使用CalendarView來顯示日曆,並加載當前日期&時間。我需要的是獲得當前日期和時間,以在我的活動中使用它們。所以,時間應該是當前時間,但用戶可以選擇另一個日期。CalendarView getDate()不返回時間

這是多麼我已經實現:

final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); 

AlertDialog diaBox = dateDialogBox(); 
diaBox.show(); 
final CalendarView calendarView = (CalendarView) diaBox.findViewById(R.id.calendarView); 

Calendar calendar = Calendar.getInstance(); 
formatedDate = sdf.format(calendar.getTime()); 
dateDialog.setTitle(formatedDate); 
dateInMillis = calendar.getTimeInMillis(); 

calendarView.setOnDateChangeListener(new OnDateChangeListener() { 
    @Override 
    public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) { 
     formatedDate = sdf.format(view.getDate()); 
     dateDialog.setTitle(formatedDate); 
     dateInMillis = calendarView.getDate(); 
    } 
}); 

當對話框提示,它得到的從日曆的日期和時間,它確實是正確的。 但是,當我選擇其他日期,它setOnDateChangeListener()進入這裏使用CalendarView獲得的日期和時間,而不是日曆的。正因爲如此,我得到的日期正確,但時間以這種方式00:00:00。

我應該怎麼做才能從CalendarView中獲取當前時間?

+0

創建基於'GETDATE一個'Calendar'對象()''從回報CalendarView' ,然後通過set()調用在'Calendar'對象上設置時間。 – CommonsWare 2014-09-23 14:44:53

回答

1

CalendarView不包含時間信息(因爲它只是日曆)。如果你想保持你的時間信息,只是可以在選定的日期,儘量使用Calender.set()方法,這樣

final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); 

AlertDialog diaBox = dateDialogBox(); 
diaBox.show(); 
final CalendarView calendarView = (CalendarView) diaBox.findViewById(R.id.calendarView); 

final Calendar calendar = Calendar.getInstance(); 
formatedDate = sdf.format(calendar.getTime()); 
dateDialog.setTitle(formatedDate); 
dateInMillis = calendar.getTimeInMillis(); 

calendarView.setOnDateChangeListener(new OnDateChangeListener() { 
    @Override 
    public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) { 
     calendar.set(year, month, dayOfMonth); 
     long selectedDateInMillis = calendar.getTimeInMillis(); 
     formatedDate = sdf.format(selectedDateInMillis); 
     dateDialog.setTitle(formatedDate); 
     dateInMillis = selectedDateInMillis; 
    } 
});