Java gets the start time, end time, current time, and whether it is in the time period of the current day.

start time of the day

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();
    }

 End Time

   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();
    }

 current time

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

 Is it in the time period

Wrote two implementations, two ways of date and 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);
    }

The advantage of localdatetime is that the code is concise, but it is inconvenient, because localdatetime must have the year, month, day, hour, minute and second.

And date is much more convenient, you can only compare hours (hourInTime), day (dayInTime), month (monthInTime) and the like, but most methods of date type are officially not recommended.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326262334&siteId=291194637