pointing to previous working day using java

前端 未结 4 1146
北恋
北恋 2020-12-18 03:43

I am new with using java.calendar.api. I want to point to the previous working day for a given day using java. BUT the conditions goes on increasing when i am using calend

相关标签:
4条回答
  • 2020-12-18 04:04

    While you should consider using the Joda Time library, here's a start with the Java Calendar API:

    public Date getPreviousWorkingDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
    
        int dayOfWeek;
        do {
            cal.add(Calendar.DAY_OF_MONTH, -1);
            dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        } while (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY);
    
        return cal.getTime();
    }
    

    This only considers weekends. You'll have to add additional checks to handle days you consider holidays. For instance you could add || isHoliday(cal) to the while condition. Then implement that method, something like:

    public boolean isHoliday(Calendar cal) {
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
    
        if (month == 12 && dayOfMonth == 25) {
            return true;
        }
    
        // more checks
    
        return false;
    }
    
    0 讨论(0)
  • 2020-12-18 04:07

    tl;dr

    LocalDate.now ( ZoneId.of ( "America/Montreal" ) )
             .with ( org.threeten.extra.Temporals.previousWorkingDay ()  )
    

    java.time

    Java 8 and later has the java.time framework built-in. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

    These new classes replace the notoriously troublesome old date-time classes bundled with the earliest versions of Java, java.util.Date/.Calendar. Avoid the old classes where possible. When you must interface look for newly added conversion methods to switch into java.time for most of your work. Also, the makers of Joda-Time have told us to move to java.time as soon as is convenient.

    Basics of java.time… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime. For a date-only value without a time-of-day nor a time zone, use LocalDate.

    First we get "today" as an example date value. Note how a time zone is required in order to determine the current date even though a LocalDate does not contain a time zone. The date is not simultaneously the same around the globe, as a new day dawns earlier in the east.

    LocalDate today = LocalDate.now ( ZoneId.of ( "America/Los_Angeles" ) );
    

    Adjustors

    The ThreeTen-Extra project extends java.time with additional or experimental features. These features may or may not eventually be folded into java.time proper. This project provides a Temporals class which provides implementations of adjustors including a couple for nextWorkingDay and previousWorkingDay. Easy to use as seen here.

    // The 'Temporals' class is from the ThreeTen-Extra library, not built into Java.
    LocalDate previousWorkingDay = today.with ( Temporals.previousWorkingDay () );
    LocalDate nextWorkingDay = today.with ( Temporals.nextWorkingDay () );
    

    When Run

    Dump to console. Notice how today is a Friday, so the previous working day is -1 (yesterday, Thursday) and the next working day is +3 (Monday).

    System.out.println ( "today: " + today + " | previousWorkingDay: " + previousWorkingDay + " | nextWorkingDay: " + nextWorkingDay );
    

    today: 2016-01-22 | previousWorkingDay: 2016-01-21 | nextWorkingDay: 2016-01-25

    Saturday & Sunday

    This pair of adjustors simply skips over every Saturday and Sunday. It knows nothing of holidays. Nor does it know about other definitions of the working week and weekend. The class documentation suggests writing your own java.time.temporal.TemporalAdjuster is easy if you want to handle other definitions.

    0 讨论(0)
  • 2020-12-18 04:11

    You may define a class as below:

    import java.util.Calendar;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     *
     * @author j.james
     */
    public class MyCalendar {
    
        private static Map<String, String> holidays = null;
        private static MyCalendar myCalendar = null;
        private static final int WEEKEND_1 = Calendar.SATURDAY;
        private static final int WEEKEND_2 = Calendar.SUNDAY;
    
        private MyCalendar() {
            holidays = new HashMap<String, String>();
            holidays.put("7,4", "Independence Day");
            holidays.put("12,25", "Christmas");
    
            //holidays.putAll(DBUtils.readAnyDynamicHolidaysFromDB());
        }
    
        public static Date getPreviousWorkingDay(Date date) {
    
            Date previousWorkingDate = null;
            try {
                if (myCalendar == null) {
                    myCalendar = new MyCalendar();
                }
    
                if(date != null) {
                    Calendar calInstance = Calendar.getInstance();
                    calInstance.setTime(date);
                    int weekDay = 0;
    
                    do {
                        calInstance.add(Calendar.DATE, -1);
                        weekDay = calInstance.get(Calendar.DAY_OF_WEEK);
                    } while(weekDay == WEEKEND_1 || weekDay == WEEKEND_2 ||
                            holidays.get((calInstance.get(Calendar.MONTH) + 1)
                            + "," + calInstance.get(Calendar.DATE)) != null);
    
                    previousWorkingDate = calInstance.getTime();
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return previousWorkingDate;
        }
    }
    

    You can make a call as

    public static void main(String[] args) {
            System.out.println(MyCalendar.getPreviousWorkingDay(new Date(2011-1900,6,5))); //July 5, 2011 which returns July 1 as the working day because July 4th 2011 is Monday
    }
    
    0 讨论(0)
  • 2020-12-18 04:15

    Consider using Joda Time combined with a list of regional holidays in your region.

    0 讨论(0)
提交回复
热议问题