Java获取当日的起始时间,结束时间,现在时间,是否在时间段中。

时间:2024-01-22 18:03:10

当日的起始时间

 public static Date getTodayStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        return todayStart.getTime();
    }

 结束时间

   public static Date getTodayEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        return todayEnd.getTime();
    }

 现在时间

 public static Date getNowDate() {
        Calendar now = Calendar.getInstance();
        return now.getTime();
    }

 是否在时间段中

写了两种实现,date和localdatetime的两种方式

    public static boolean inTime(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean hourInTime(Date beginTime, Date endTime) {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        Date nowTime = null;
        try {
            nowTime = df.parse(df.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return inTime(nowTime, beginTime, endTime);
    }

    public static boolean inTime(LocalDateTime time, LocalDateTime beginTime, LocalDateTime endTime) {
        return (time.isAfter(beginTime) && time.isBefore(endTime));
    }

    public static boolean hourInTime(LocalDateTime beginTime, LocalDateTime endTime) {
        return inTime(LocalDateTime.now(), beginTime, endTime);
    }

localdatetime的优点就是代码简洁,但是不方便,因为localdatetime一定是带年月日时分秒的。

而date则方便了许多,可以只比较时分(hourInTime),日(dayInTime),月(monthInTime)之类的,但是date类型大多数方法官方不建议使用。