【问题标题】:Compare string time with current time android比较字符串时间与当前时间android
【发布时间】:2015-08-08 14:11:21
【问题描述】:

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

【问题讨论】:

    标签: android string time android-notifications


    【解决方案1】:

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

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

    在你的情况下,如果我得到正确的东西,你有两个时间点(小时和分钟对 -- HH:MM -- time1 和 time2)来比较,你要确保当前时间在该范围内对吧?

    在这种情况下,我会使用 JodaTime 的 LocalTime 类并将当前时间与 time1 和 time2 进行比较。

    它可能看起来像这样:

    LocalTime currentTime = new LocalTime();
    LocalTime time1 = new LocalTime(selectedhour1, selectedminute1);
    LocalTime time2 = new LocalTime(selectedhour2, selectedminute2);
    
    if (currenTime >= time1 && currentTime <= time2) {
        // show your notification
    }
    

    【讨论】:

    • 谢谢!!你做对了,它真的很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    相关资源
    最近更新 更多