如何检查时间在 android 的两个时间之间

How to check time is between two time only night in android

在我的 android 应用程序中,如果选择的时间大于 11:00 PM 和 07:00 AM,则需要支付额外费用。它只适用于晚上。目前,我的代码可以正常工作,但是当我选择一天中的某个时间时,情况会变得真实。

这是我的代码

 Calendar calendar = Calendar.getInstance();


                String startDatetime = "11:00 PM";
                String endDatetime = "07:00 AM";
                SimpleDateFormat formatfornightcharges = new SimpleDateFormat("HH:mm aa");
                int Hr24 = calendar.get(Calendar.HOUR_OF_DAY);

                try {
                    Date startDate = formatfornightcharges.parse(startDatetime);
                    Date selectedTimeforBooking = formatfornightcharges.parse(time_for_night);
                    Date endDate = formatfornightcharges.parse(endDatetime);
                        if (selectedTimeforBooking.after(startDate) || selectedTimeforBooking.before(endDate)) {
                            Toast.makeText(context, "200", Toast.LENGTH_SHORT).show();
                            night_extra_charges = 200;
                            tv_text.setText("" + night_extra_charges);
                        } else {
                            night_extra_charges = 0;
                            tv_text.setText("" + night_extra_charges);
                            Toast.makeText(context, "0", Toast.LENGTH_SHORT).show();
                        }


                } catch (ParseException e) {
                    e.printStackTrace();
                }


            }

您只需要将格式化程序更改为:

SimpleDateFormat formatfornightcharges = new SimpleDateFormat("hh:mm aa", Locale.US);

而不是 "hh:MM aa"

试试这个,它一直有效,只改变 time_for_night 这种格式:-

String startDatetime = "11:00 PM";
        String endDatetime = "07:00 AM";
        String time_for_night = "11:05 PM";
        Integer night_extra_charges=0;
        SimpleDateFormat formatfornightcharges = new SimpleDateFormat("hh:mm aa", Locale.ENGLISH);
        try {
            Date startDate = formatfornightcharges.parse(startDatetime);
            Date selectedTimeforBooking = formatfornightcharges.parse(time_for_night);
            Date endDate = formatfornightcharges.parse(endDatetime);
            if ((selectedTimeforBooking.after(startDate)) || (selectedTimeforBooking.before(endDate))) {
                Toast.makeText(ScanDocumentsActivity.this, "200", Toast.LENGTH_SHORT).show();
                night_extra_charges = 200;
                Log.wtf("night_extra_charges",""+night_extra_charges);
            } else {
                night_extra_charges = 0;
                Log.wtf("night_extra_charges",""+night_extra_charges);
                Toast.makeText(ScanDocumentsActivity.this, "0", Toast.LENGTH_SHORT).show();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }