将字符串时间与当前时间进行比较 android

Compare string time with current time android

我有 2 个来自 timepickerdialog 的字符串格式的时间。我无法弄清楚如何将我的第一个字符串时间与当前时间进行比较。在 time1-time2 期间我想显示一个简单的通知。我已经阅读了很多文档,但没有运气。也许详细的教程或源代码会有所帮助。

提前致谢

这是我的代码:

 final Button time1 = (Button) findViewById(R.id.button1);       
    time1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar now = Calendar.getInstance();
            TimePickerDialog dpd = TimePickerDialog.newInstance(
                    Scheduler.this,
                    now.get(Calendar.HOUR_OF_DAY),
                    now.get(Calendar.MINUTE), true
            );
            dpd.show(getFragmentManager(), "Timepickerdialog");
            dpd.setOnTimeSetListener(new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(RadialPickerLayout radialPickerLayout, int selectedhour, int selectedminute) {
                    time1.setText(pad(selectedhour) + " : " + pad(selectedminute));      

                }
            });
        }
    });


    final Button time2 = (Button) findViewById(R.id.button2);       
    time2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar now = Calendar.getInstance();
            TimePickerDialog dpd = TimePickerDialog.newInstance(
                    Scheduler.this,
                    now.get(Calendar.HOUR_OF_DAY),
                    now.get(Calendar.MINUTE), true
            );

            dpd.show(getFragmentManager(), "Timepickerdialog");
            dpd.setOnTimeSetListener(new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(RadialPickerLayout radialPickerLayout, int selectedhour, int selectedminute) {
                    time2.setText(pad(selectedhour) + " : " + pad(selectedminute));
                }
            });
        }
    });

有一个优秀的 JodaTime 库用于与时间相关的操作,它甚至具有 Android 风格,这里有一个 link 给你:

https://github.com/dlew/joda-time-android

在你的情况下,如果我得到的东西是正确的,你有两个时间点(小时和分钟对 -- HH:MM -- 时间 1 和时间 2)进行比较,你要确定当前时间是在这个范围内吧?

在这种情况下,我将使用 JodaTime 的 LocalTime class 并将当前时间与时间 1 和时间 2 进行比较。

它可能看起来像这样:

LocalTime currentTime = new LocalTime();
LocalTime time1 = new LocalTime(selectedhour1, selectedminute1);
LocalTime time2 = new LocalTime(selectedhour2, selectedminute2);

if (currenTime >= time1 && currentTime <= time2) {
    // show your notification
}