android 中的时间,在某些情况下有效,在其他情况下失败

Time in android,works in some cases, fails in other

我们可以从给定的时段中选择任何时间。如果选择的时间比当前时间少 1 小时,那么我们必须显示警报。下面是我写的。但它不完全 correct.In 在某些情况下它有效

    String Date = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());
    //to get current date
    String Time = new SimpleDateFormat("hh:mm a").format(new Date());
    //to get current time

    String DeliveryDate=deliveryDate.getText().toString();

    if (Date.equals(DeliveryDate)) {
        //comparing current date and delivery date,delivery date choosen from calendar
        if (deliveryTimeText.compareTo(currentTime) < 3)
        {
             showToast("Sorry! Delivery Time is less by 1 hour. Cannot place order");
        }
    }

使用 SimpleDateFormatDate class 中转换您的 deliveryDateTime。 前任。

try {
            if (currentDate.equals(DeliveryDate)) {
                String deliveryTime = "1:00 PM";
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                        "hh:mm a", Locale.ENGLISH);

                java.util.Date currentDate = simpleDateFormat.parse(deliveryTime);
                Calendar curDate= Calendar.getInstance();
                curDate.setTime(currentDate);
                Calendar currentDateDelivery= Calendar.getInstance();
                currentDateDelivery.set(Calendar.HOUR_OF_DAY,
                        curDate.get(Calendar.HOUR_OF_DAY));
                currentDateDelivery.set(Calendar.MINUTE,
                        curDate.get(Calendar.MINUTE));

                Calendar threeHoursLaterTime = Calendar.getInstance();
                threeHoursLaterTime.add(Calendar.HOUR_OF_DAY, 3);
                if (currentDateDelivery.getTimeInMillis() < threeHoursLaterTime
                        .getTimeInMillis()) {
                    showToast(
                            "Sorry! Delivery Time is less than 3 hours.Cannot place order");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }