OpenHarmony ArkTS 有类似于java的Time类吗,判断当前时间段是否在两个时间段之内

luke 显示全部楼层 发表于 2023-12-5 13:33:11
类似于实现这个方法

 boolean result = false;
        try{
            int beginHour = 00;
            int beginMin = 00;
            int beginSecond = 00;
            int endHour = 00;
            int endMin = 00;
            int endSecond = 00;
            beginHour = Integer.valueOf(newBeginTime.split(":")[0]);
            beginMin = Integer.valueOf(newBeginTime.split(":")[1]);
            beginSecond = Integer.valueOf(newBeginTime.split(":")[2]);
            endHour = Integer.valueOf(newEndTime.split(":")[0]);
            endMin = Integer.valueOf(newEndTime.split(":")[1]);
            endSecond = Integer.valueOf(newEndTime.split(":")[2]);

            final long aDayInMillis = 1000 * 60 * 60 * 24;
            final long currentTimeMillis = System.currentTimeMillis();

            Time now = new Time();
            now.set(currentTimeMillis);
            Time startTime = new Time();
            startTime.set(currentTimeMillis);
            startTime.hour = beginHour;
            startTime.minute = beginMin;
            startTime.second = beginSecond;
            Time endTime = new Time();
            endTime.set(currentTimeMillis);
            endTime.hour = endHour;
            endTime.minute = endMin;
            endTime.second = endSecond;
            if (!startTime.before(endTime)) {
                // 跨天的特殊情况(比如22:00-8:00)
                startTime.set(startTime.toMillis(true) - aDayInMillis);
                result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
                Time startTimeInThisDay = new Time();
                startTimeInThisDay.set(startTime.toMillis(true) + aDayInMillis);
                if (!now.before(startTimeInThisDay)) {
                    result = true;
                }
            } else {
                // 普通情况(比如 8:00 - 14:00)
                result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }

//        Log.e("---",">>>"+result);
        return result;
您尚未登录,无法参与评论,登录后可以:
参与开源共建问题交流
认同或收藏高质量问答
获取积分成为开源共建先驱

精彩评论1

马迪

沙发 发表于 2023-12-5 15:16:42
  1. const startTime = new Date('2023-03-17T09:00:00');  
  2. const endTime = new Date('2023-03-17T17:00:00');  
  3. const checkTime = new Date('2023-03-17T12:30:00');  
  4.   
  5. if (checkTime >= startTime && checkTime <= endTime) {  
  6.   console.log('The check time is within the specified time range.');  
  7. } else {  
  8.   console.log('The check time is outside the specified time range.');  
  9. }
复制代码

Copyright   ©2023  OpenHarmony开发者论坛  京ICP备2020036654号-3 |技术支持 Discuz!

返回顶部