代码之家  ›  专栏  ›  技术社区  ›  t0thkr1s

比较字符串时间与当前时间android

  •  1
  • t0thkr1s  · 技术社区  · 10 年前

    我从timepickerdialog中获得了2次字符串格式的时间。我想不通 如何将我的第一个字符串时间与当前时间进行比较 在时间1到时间2之间,我想显示一个简单的通知。我读了很多文档,但运气不佳。也许详细的教程或源代码会有所帮助。

    提前感谢

    这是我的代码:

     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));
                    }
                });
            }
        });
    
    1 回复  |  直到 10 年前
        1
  •  1
  •   pelotasplus    10 年前

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

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

    在你的例子中,如果我正确地理解了事情,你有两个时间点(小时和分钟对--HH:MM--time1和time2)需要比较,你需要做什么来确保当前时间在这个范围内,对吗?

    在这种情况下,我会使用JodaTime的 LocalTime 分类并将当前时间与时间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
    }