18

In my app, I am showing time in text view as 07:00 PM. On click of the text view, a time picker dialog pops up, In that time picker, I have to show exactly the same time as what is appearing in textview. But, I am not getting how to do that.

CODE

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm a");
        //int hr = 0;
        Date date = null;
        try 
        {
            date = sdf.parse(resDateArray[3]);
        } 
        catch (ParseException e) {
            e.printStackTrace();
        }
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //tp is reference variable for time picker

        tp.setCurrentHour(calendar.get(Calendar.HOUR));
        tp.setCurrentMinute(calendar.get(Calendar.MINUTE));

        }//else
Nitish
  • 3,097
  • 13
  • 45
  • 80

7 Answers7

38

You should use a SimpleDateFormat to get a Date object from your String. Then just call

picker.setCurrentHour(date.getHours())

and

picker.setCurrentMinute(date.getMinutes())

Since the Date object is deprecated, you should use a Calendar instead of it. You can instantiate a Calendar this way:

Calendar c = Calendar.getInstance();
c.setTime(date);
picker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
picker.setCurrentMinute(c.get(Calendat.MINUTE));

Edit: the complete code:

import java.util.Date;
import java.text.SimpleDateFormat; //Don't use "android.icu.text.SimpleDateFormat"
import java.text.ParseException; //Don't use "android.net.ParseException"

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
Date date = null;
try {
    date = sdf.parse("07:00");
} catch (ParseException e) {
}
Calendar c = Calendar.getInstance();
c.setTime(date);

TimePicker picker = new TimePicker(getApplicationContext());
picker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
picker.setCurrentMinute(c.get(Calendar.MINUTE));
Neph
  • 1,823
  • 2
  • 31
  • 69
abecker
  • 885
  • 1
  • 10
  • 15
  • Did it, but time I am showing is PM. So, how can show the time in AM/PM? – Nitish Sep 19 '12 at 17:35
  • 1
    With the SimpleDateFormat, you can use a format String that allow for using "AM/PM" date format. Like : SimpleDateFormat sdf = new SimpleDateFormat("hh:ss a"); date = sdf.parse("07:00 AM"); Then use Calendar.HOUR instead of Calendat.HOUR_OF_DAY in order to get AM/PM hour format – abecker Sep 19 '12 at 18:29
  • 1
    You should use "hh:mm a" instead of "HH:mm a" because "HH" represents the hour in day (0-23). Take a look at the doc below : http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html – abecker Sep 20 '12 at 07:40
  • Thanks, it solved my problem actually, I was doing it in wrong way. – Nitish Sep 20 '12 at 18:28
  • 1
    The `setCurrent...` methods are deprecated since API 23, use `setHour` & `setMinute` instead! – Neph Mar 09 '20 at 15:54
4

If anybody using the following format that is without using timepicker widget use this one..

mStartTime.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            new TimePickerDialog(AddAppointmentActivity.this, onStartTimeListener, calendar
                    .get(Calendar.HOUR), calendar.get(Calendar.MINUTE), false).show();

        }
    });

TimePickerDialog.OnTimeSetListener onStartTimeListener = new OnTimeSetListener() {

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        String AM_PM;
        int am_pm;

        mStartTime.setText(hourOfDay + " : " + minute + "  " + AM_PM);
        calendar.set(Calendar.HOUR, hourOfDay);
        calendar.set(Calendar.MINUTE, minute);

    }
};
Aravin
  • 4,126
  • 1
  • 23
  • 39
4

I have created this helper function to get time

        public static void showTime(final Context context, final TextView textView) {

    final Calendar myCalendar = Calendar.getInstance();
    TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            String am_pm = "";
            myCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            myCalendar.set(Calendar.MINUTE, minute);
            if (myCalendar.get(Calendar.AM_PM) == Calendar.AM)
                am_pm = "AM";
            else if (myCalendar.get(Calendar.AM_PM) == Calendar.PM)
                am_pm = "PM";
            String strHrsToShow = (myCalendar.get(Calendar.HOUR) == 0) ? "12" : myCalendar.get(Calendar.HOUR) + "";
            //UIHelper.showLongToastInCenter(context, strHrsToShow + ":" + myCalendar.get(Calendar.MINUTE) + " " + am_pm);
            textView.setText(strHrsToShow + ":" + myCalendar.get(Calendar.MINUTE) + " " + am_pm);
        }
    };
    new TimePickerDialog(context, mTimeSetListener, myCalendar.get(Calendar.HOUR), myCalendar.get(Calendar.MINUTE), false).show();
}

and How to get current time in required format, I use following code. // PARAM Date is date of time you want to format // PARAM currentFormat of date // PARAM requiredFormat of date

    public static String getFormattedDate(String date, String currentFormate, String requiredFormate) {
    //SimpleDateFormat formatActual = new SimpleDateFormat("yyyy - MM - dd");
    if (date != null) {
        SimpleDateFormat formatActual = new SimpleDateFormat(currentFormate);
        Date dateA = null;
        try {
            dateA = formatActual.parse(date);
            System.out.println(dateA);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //SimpleDateFormat formatter = new SimpleDateFormat("dd MMM, yyyy");
        SimpleDateFormat formatter = new SimpleDateFormat(requiredFormate);
        String format = formatter.format(dateA);
        System.out.println(format);
        return format;
    } else {
        return "";
    }

}

usage of getFormattedDate is:

       String date = getFormattedDate(dateYouWantToFormate,"hh:mm a","hh:mm");
Faraz Ahmed
  • 1,245
  • 1
  • 14
  • 24
2

If you're using the TimePicker nowdays its probably best to check the Build Version as the setCurrentHour and setCurrentMinute has been deprecated.

SimpleDateFormat sdf = new SimpleDateFormat("hh:ss");
Date date = null;
try {
    date = sdf.parse("07:00");
} catch (ParseException e) {
}
Calendar c = Calendar.getInstance();
c.setTime(date);

TimePicker timePicker = new TimePicker(getApplicationContext());

if (Build.VERSION.SDK_INT >= 23) {
    timePicker.setHour(calculateHours());
    timePicker.setMinute(calculateMinutes());
}
else {
    timePicker.setCurrentHour(calculateHours());
    timePicker.setCurrentMinute(calculateMinutes());
}
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Brandon
  • 1,158
  • 3
  • 12
  • 22
  • Do you think there is a better way to handle this check? Running this if-else check for every time picker in the app can be tedious – baskInEminence Sep 09 '20 at 04:56
  • 1
    You could create your own TimePicker class with set hours and minutes methods, then have the class itself handle the logic and assigned the correct one accordingly, another similar option could be extension methods – Brandon Sep 09 '20 at 05:28
  • 1
    Yeah that would work fine. I tried the extension but it seems android studio still produces a warning because it references deprecated code. I guess android studio isn't smart enough to understand we are handling this properly? – baskInEminence Sep 09 '20 at 14:48
  • @baskInEminence Another weird thing is that the deprecated functions call the new functions, so it makes this check seem redundant. It's really unclear how we should handle it. – John May 11 '21 at 17:01
2

One important point has to be kept in mind while retrieving time in onTimeSet() function, there is no special function to set AM_PM in the calendar instance. When we set the time AM_PM is automatically set accordingly like if AM was selected while choosing hour and minute then <calendarVariable>.get(Calendar.AM_PM) will return 0 and in opposite case (in case of PM) it will return 1.

csabinho
  • 1,579
  • 1
  • 18
  • 28
striker
  • 560
  • 6
  • 13
1

Some changes after sdk version 23;

            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
            Date date = null;
            try {
                date = sdf.parse("12:02:32");
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(date != null) {
                Calendar c = Calendar.getInstance();
                c.setTime(date);
                sleepTimeStartPicker.setHour(c.get(Calendar.HOUR_OF_DAY));
                sleepTimeStartPicker.setMinute(c.get(Calendar.MINUTE));
            }
Savas Adar
  • 4,083
  • 3
  • 46
  • 54
0

For AM/PM you have to implement a logic for that and that is as below.. so you can get the output as you mentioned ... just try below code...

int hr=tp.getCurrentHour();
String a="AM";
if(hr>=12){
    hr=hr-12;
    a="PM";
}
String tm=hr+":"+tp.getCurrentMinute()+" "+a;

Toast.makeText(MainActivity.this, tm, 500).show();