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

前端 未结 2 1863
后悔当初
后悔当初 2020-12-18 02:27

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:

相关标签:
2条回答
  • 2020-12-18 02:42

    The java.util.Date class is a container that holds a number of milliseconds since 1 January 1970, 00:00:00 UTC. Note that class Date doesn't know anyting about timezones. Use class Calendar if you need to work with timezones. (edit 19-Jan-2017: if you are using Java 8, use the new date and time API in package java.time).

    Class Date is not really suited for holding an hour number (for example 13:00 or 18:00) without a date. It's simply not made for that purpose, so if you try to use it like that, as you seem to be doing, you'll run into a number of problems and your solution won't be elegant.

    If you forget about using class Date to store the working hours and just use integers, this will be much simpler:

    Date userDate = ...;
    TimeZone userTimeZone = ...;
    
    int companyWorkStartHour = 13;
    int companyWorkEndHour = 18;
    
    Calendar cal = Calendar.getInstance();
    cal.setTime(userDate);
    cal.setTimeZone(userTimeZone);
    
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    boolean withinCompanyHours = (hour >= companyWorkStartHour && hour < companyWorkEndHour);
    

    If you also want to take minutes (not just hours) into account, you could do something like this:

    int companyWorkStart = 1300;
    int companyWorkEnd = 1830;
    
    int time = cal.get(Calendar.HOUR_OF_DAY) * 100 + cal.get(Calendar.MINUTE);
    boolean withinCompanyHours = (time >= companyWorkStart && time < companyWorkEnd);
    
    0 讨论(0)
  • 2020-12-18 02:48

    Try something like this:

    Calendar companyWorkStart = new GregorianCalendar(companyTimeZone);
    companyWorkStart.setTime(companyWorkStartHour);
    
    Calendar companyWorkEnd = new GregorianCalendar(companyTimeZone);
    companyWorkEnd.setTime(companyWorkEndHour);
    
    Calendar user = new GregorianCalendar(userTimeZone);
    user.setTime(userTime);
    
    if(user.compareTo(companyWorkStart)>=0 && user.compareTo(companyWorkEnd)<=0) {
      ...
    }
    
    0 讨论(0)
提交回复
热议问题