从DateTime选择器获得12小时的时间

时间:2017-05-20 16:49:47

标签: java android datetime

我使用Material DateTime选择器来选择日期和时间。它工作正常,但在onTimeSetListener方法中,它以24小时格式返回hourOfTheDay

我想把它显示为12小时格式,因为我使用if条件,其中小时数大于12,那么它应该显示PM,但小时数不会改变。

我该如何更改?

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 );
    }
}

请帮忙。谢谢。

2 个答案:

答案 0 :(得分:1)

我认为您的if声明无效:



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

答案 1 :(得分:1)

您无需重新发明轮子。特别是,如果您的应用程序正在使用日期和时间,您应该考虑使用ThreeTenABP库并使用现代Java日期和时间类。其中一个LocalTime,用两行解决你的任务:

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

迁移到Java 8后,这些类是内置的,您可以丢弃该库。

如果您不希望依赖于另外一个外部库,您可以使用过时的类GregorianCalendarDateSimpleDateFormat获得相同的内容,只有它会更少优雅,远非面向未来。

链接