1

I am using Material DateTime picker for choosing date and time. Its working fine, but in onTimeSetListener method it returns hourOfTheDay in 24 hours format.

I want to show it it 12 hour format for that I used the if condition where hours are greater than 12 then it should show PM, but the hour number dose not change.

How can I change this?

public class TransportFragment extends Fragment implements DatePickerDialog.OnDateSetListener,TimePickerDialog.OnTimeSetListener {


    private OnFragmentInteractionListener mListener;
    private EditText mEditTxt_From,mEditTxt_To,mEditTxt_DateTime;
    int PLACE_PICKER_REQUEST = 1;

    private static final String TAG = "PlacePickerSample";

    private static final int REQUEST_PLACE_PICKER_FROM = 1;
    private static final int REQUEST_PLACE_PICKER_TO = 2;

    private String mDate;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_transport, container, false);

        mEditTxt_From = (EditText) view.findViewById(R.id.editTextFrom);
        mEditTxt_To = (EditText) view.findViewById(R.id.editTextTo);
        mEditTxt_DateTime = (EditText) view.findViewById(R.id.editTextDateTime);


        mEditTxt_DateTime = (EditText) view.findViewById(R.id.editTextDateTime);


        mEditTxt_DateTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Calendar now = Calendar.getInstance();
                DatePickerDialog dpd = DatePickerDialog.newInstance(
                        TransportFragment.this,
                        now.get(Calendar.YEAR),
                        now.get(Calendar.MONTH),
                        now.get(Calendar.DAY_OF_MONTH)
                );

                dpd.setVersion(DatePickerDialog.Version.VERSION_2);

                dpd.setAccentColor(ContextCompat.getColor(getActivity(),R.color.colorAccent));

                dpd.show(getFragmentManager(), "Datepickerdialog");
            }
        });

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        mDate = dayOfMonth+"/"+(++monthOfYear)+"/"+year;

        Calendar now = Calendar.getInstance();

        TimePickerDialog tpd = TimePickerDialog.newInstance(
                TransportFragment.this,
                now.get(Calendar.HOUR_OF_DAY),
                now.get(Calendar.MINUTE),
                false
        );


        tpd.setVersion(TimePickerDialog.Version.VERSION_2);

        tpd.setAccentColor(ContextCompat.getColor(getActivity(),R.color.colorAccent));

        tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                Log.d("TimePicker", "Dialog was cancelled");
            }
        });
        tpd.show(getFragmentManager(), "Timepickerdialog");
    }

    @Override
    public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
        String hourString = hourOfDay < 10 ? "0"+hourOfDay : ""+hourOfDay;
        String minuteString = minute < 10 ? "0"+minute : ""+minute;
        String secondString = second < 10 ? "0"+second : ""+second;

        String time;

        if(hourOfDay > 12)
        {
            time = hourOfDay + ":" + minuteString + " PM";
        }
        else {

            time = hourOfDay + ":" + minuteString + " AM";
        }

        mEditTxt_DateTime.setText(mDate + "  " + time );
    }
}

Please help. Thank you.

azizbekian
  • 60,783
  • 13
  • 169
  • 249
Sid
  • 2,792
  • 9
  • 55
  • 111
  • Too much irrelevant code. A Question on Stack Overflow should be narrowly focused with a minimum of code to demonstrate your issue. See [MCVE](https://stackoverflow.com/help/mcve) – Basil Bourque May 20 '17 at 22:12

2 Answers2

1

I think your if statement is invalid:



    if (hourOfDay > 12) {
        time = (hourOfDay - 12)  + ":" + minuteString + " PM";
    } else {
       ...
    }

azizbekian
  • 60,783
  • 13
  • 169
  • 249
1

You do not need to reinvent the wheel. In particular, if your app is working with dates and times, you should consider getting the ThreeTenABP library and using the modern Java date and time classes. One of these, LocalTime, solves your task in two lines:

    DateTimeFormatter twelveHourTimeFormatter
            = DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.ENGLISH);
    String time = LocalTime.of(hourOfDay, minute, second)
            .format(twelveHourTimeFormatter);

Once you move to Java 8 the classes are built-in and you can discard the library.

In case you don’t want the dependency on one more external library, you can obtain the same with the outdated classes GregorianCalendar, Date and SimpleDateFormat, only it will be less elegant and far from future-proof.

Links

Community
  • 1
  • 1
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161