0

I am using this code to get the time from the Time Picker. . .

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this,mTimeSetListener, Calendar.HOUR, Calendar.MINUTE, false);
    }
    return null;
}

private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            reminderSetTime.setText(""+hourOfDay+":"+minute+"");
            Toast.makeText(ImportantDateReminderActivity.this, "Time is="+hourOfDay+":"+minute, Toast.LENGTH_SHORT).show();
        }
    };

static final int TIME_DIALOG_ID = 0;

And to Display the TimePicker i use below code:

    case R.id.reminderTime:
            showDialog(TIME_DIALOG_ID);
            break;

With doing that i am not getting the proper value of the time. I want the Value like 1:00 PM and 10:00 AM But i am not getting PM/AM and if the time is more then 12 then i am getting 13,14. . . like figure. instead of that i want the figure in 1 to 12.

So how to set that value ?? Thanks.

Shreyash Mahajan
  • 23,386
  • 35
  • 116
  • 188

3 Answers3

2
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mHour = hourOfDay;
            mMinute = minute;
            if(mHour==12)
                btnFromTime.setText(new StringBuilder().append("12").append(":").append(pad(minute)+" PM"));
        else
            updateTimeDisplay();
        }
    };

this is working for me...

and use this

private void updateTimeDisplay() {

        try {
            Format formatter;
            SimpleDateFormat df = new SimpleDateFormat("hh:mm");
            Date d = df.parse(mHour + ":" + mMinute);
            Calendar gc = new GregorianCalendar();
            gc.setTime(d);
            gc.add(Calendar.HOUR, 0);
            Date d2 = gc.getTime();
            formatter = new SimpleDateFormat("hh:mm a");
            String time = formatter.format(d2);

            btnFromTime.setText(time);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
NikhilReddy
  • 6,904
  • 11
  • 38
  • 58
1

Did you try: TimePicker.setIs24HourView(false) ?

teoREtik
  • 7,886
  • 15
  • 46
  • 65
1

It's Androids best practice to do whatever the user wants; what is set in the Android settings:

How to get user-selected date format in Android?

Check TIME_12_24

Answer to you question, you can use the DateFormat class to achive what you want

Community
  • 1
  • 1
Jordi
  • 1,357
  • 12
  • 20