【问题标题】:CalendarView getDate() does not return timeCalendarView getDate() 不返回时间
【发布时间】:2014-09-23 14:41:08
【问题描述】:

我正在使用 CalendarView 来显示日历,并加载当前日期和时间。我需要的是获取当前日期和时间以在我的活动中使用它们。因此,时间应该是当前时间,但用户可以选择另一个日期。

这就是我的实现方式:

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 而不是 Calendar 来获取日期和时间。因此,我正确获取了日期,但时间以 00:00:00 的方式显示。

我应该怎么做才能从 CalendarView 中获取当前时间?

【问题讨论】:

  • 根据CalendarView返回的getDate()创建一个Calendar对象,然后通过set()调用在Calendar对象上设置时间。

标签: android date


【解决方案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;
    }
});

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    相关资源
    最近更新 更多