时间和日期选择器android

时间:2015-01-10 13:49:57

标签: android datetime time

我正在研究Android应用程序,我想在其中选择日期和时间。我正在使用以下方法来获得对话框的时间。但是,当我点击时间对话框时,我想做类似的事情,它也会显示日期。请帮帮我:

private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {


            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minutes) {
                // TODO Auto-generated method stub
                hour   = hourOfDay;
                minute = minutes;

                updateTime(hour,minute);

             }

        };

        private static String utilTime(int value) {

            if (value < 10)
                return "0" + String.valueOf(value);
            else
                return String.valueOf(value);
        }
    // Used to convert 24hr format to 12hr format with AM/PM values
    private void updateTime(int hours, int mins) {

        String timeSet = "";
        if (hours > 12) {
            hours -= 12;
            timeSet = "PM";
        } else if (hours == 0) {
            hours += 12;
            timeSet = "AM";
        } else if (hours == 12)
            timeSet = "PM";
        else
            timeSet = "AM";


        String minutes = "";
        if (mins < 10)
            minutes = "0" + mins;
        else
            minutes = String.valueOf(mins);

        // Append in a StringBuilder
         String aTime = new StringBuilder().append(hours).append(':')
                .append(minutes).append(" ").append(timeSet).toString();

          txtTimePicker.setText(aTime);
    }
 @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case TIME_DIALOG_ID:

                // set time picker as current time
                return new TimePickerDialog(this, timePickerListener, hour, minute,
                        false);

            }
            return null;
        }

2 个答案:

答案 0 :(得分:0)

如果您同时需要时间选择器和日期选择器,则需要使用两个不同的对话框类:TimePickerDialogDatePickerDialog

因此,如果您希望用户也选择日期,则需要在显示时间选择器之前或之后显示DatePickerDialog。您可以像显示TimePickerDialog一样显示DatePickerDialog。

答案 1 :(得分:0)

根据您的要求输入以下代码:

SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); 

        try {
            dateObj = curFormater.parse(dateStr);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
         SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy"); 

         String newDateStr = postFormater.format(dateObj); 

         txtTimePicker.setText(newDateStr+" "+aTime);