欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java,android:判断当前时间是否属于该时间段

程序员文章站 2022-06-22 10:00:51
自己写的一方法 /** * judge the current time is on the time, for example: current is 11:00, startTimeStringFormat=10:00,endTimeStringFormat==12:00,you will get true * * @param startTimeStringFormat String:"HH:mm" you must follow the format...

自己写的一方法

    /**
     * judge the current time is on the time, for example: current is 11:00, startTimeStringFormat=10:00,endTimeStringFormat==12:00,you will get true
     *
     * @param startTimeStringFormat String:"HH:mm" you must follow the format
     * @param endTimeStringFormat   String:"HH:mm" you must follow the format
     * @return boolean: if the the current time on the range
     * @throws Exception : simpleDateFormat.parse maybe null, simpleDateFormat.parse mayby exception
     */
    public static boolean currentTimebelongTheRange(String startTimeStringFormat, String endTimeStringFormat) throws Exception {
        String dateFormatString = "HH:mm";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatString);

        //first get now time calendar
        String nowTimeFormat = simpleDateFormat.format(new Date());
        Date nowTimeData = simpleDateFormat.parse(nowTimeFormat);
        Calendar nowTimeCalendar = Calendar.getInstance();
        nowTimeCalendar.setTime(Objects.requireNonNull(nowTimeData));

        //second get start time calendar
        Date startTimeData = simpleDateFormat.parse(startTimeStringFormat);
        Calendar startTimeCalendar = Calendar.getInstance();
        startTimeCalendar.setTime(Objects.requireNonNull(startTimeData));

        //third get end time calendar
        Date endTimeData = simpleDateFormat.parse(endTimeStringFormat);
        Calendar endTimeCalendar = Calendar.getInstance();
        endTimeCalendar.setTime(Objects.requireNonNull(endTimeData));

        return nowTimeCalendar.after(startTimeCalendar) && nowTimeCalendar.before(endTimeCalendar);
    }

本文地址:https://blog.csdn.net/qq_36017059/article/details/110631471

相关标签: java android