我如何比较Java中的两个小时? [英] How can I compare two hours in java?

查看:65
本文介绍了我如何比较Java中的两个小时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算餐厅的营业时间.我有两个字符串,例如:

I want to calculate restaurant's opened hours. I have two string, for example:

String start_hour = "09:00";
String end_hour = "18:00";

以当前小时为例:

    Calendar now = Calendar.getInstance();
    String current_hour = now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE);

I calculate open hours with this method:

    public boolean isRestaurantOpenNow() {
            try {
                Calendar now = Calendar.getInstance();
                String current_hour = now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE);
                String st_hour = "09:00";
                String en_hour = "18:00";
                @SuppressLint("SimpleDateFormat") final SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                Date sth = null;
                sth = format.parse(st_hour);
                Date enh = format.parse(en_hour);
                Date nowh = format.parse(current_hour );
                if (nowh != null) {
                    if (nowh.before(enh) && nowh.after(sth)) {
                        // restaurant is open
                        return true;
                    } else {
                        // restaurant is close
                        return false;
                    }
                }
            } catch (ParseException ignored) {
            }
            return false;
        }

但是我有一些问题.当 start_hour 为 "13:00" 和 end_hour "05:00" 时,此方法会出错.因为从第二天 05:00 开始.我该如何解决这个问题?

But I have some problem with that. This method working wrong when start_hour is "13:00" and end_hour "05:00". Because 05:00 hour from next day. How can I solve this problem?

推荐答案

代替

nowh.before(enh) && nowh.after(sth)

使用

nowh.before(enh) && nowh.after(sth) && sth.before(enh)
|| enh.before(sth) && !(nowh.before(enh) && nowh.after(sth))

除此之外,我认为应该以不同的方式使用 Calendar 类...

Apart from that I think Calendar class is supposed to be used differently I assume...

这篇关于我如何比较Java中的两个小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆