Struggling with how to compare hours with different time zones in Java?

前端 未结 4 831
遥遥无期
遥遥无期 2020-12-18 02:33

I have 2 date object in the database that represent the company\'s working hours.

I only need the hours but since I have to save date. it appears like this:

4条回答
  •  [愿得一人]
    2020-12-18 02:58

    I haven't tried the Joda library. This code should work.

    public boolean checkUserTimeZoneOverLaps(TimeZone companyTimeZone,
            TimeZone userTimeZone, Date companyWorkStartHour,
            Date companyWorkEndHour, Date userCurrentDate) {
    
        Calendar userCurrentTime = Calendar.getInstance(userTimeZone);
        userCurrentTime.setTime(userCurrentDate);
        int year = userCurrentTime.get(Calendar.YEAR);
        int month = userCurrentTime.get(Calendar.MONTH);
        int day = userCurrentTime.get(Calendar.DAY_OF_MONTH);
    
        Calendar startTime = Calendar.getInstance(companyTimeZone);
        startTime.setTime(companyWorkStartHour);
        startTime.set(Calendar.YEAR, year);
        startTime.set(Calendar.MONTH, month);
        startTime.set(Calendar.DAY_OF_MONTH, day);
    
        Calendar endTime = Calendar.getInstance(companyTimeZone);
        endTime.setTime(companyWorkEndHour);
        endTime.set(Calendar.YEAR, year);
        endTime.set(Calendar.MONTH, month);
        endTime.set(Calendar.DAY_OF_MONTH, day);
    
        if (userCurrentTime.after(startTime) && userCurrentTime.before(endTime)) {
            return true;
        }
        return false;
    }
    

    EDIT Updated the code to reflect Bruno's comments. Shouldn't be taking the dates of the company work timings.

提交回复
热议问题