You are here
Home >

Important Utility Methods

Q. How to get last 10 business days(excluding Holidays & weekends) in java?

A.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

public class ListBusinessDays {  
 private static List getBuDays() throws ParseException{  
      String date="";        
      List list= new ArrayList();      
      String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());                
       for (int i = 0; i >= -9; i--) {            
       if (i == 0) {                
        Date recvdDate = new SimpleDateFormat("yyyy-MM-dd").parse(currentDate); 
               Calendar c = new GregorianCalendar();             
               c.setTime(recvdDate);    
               if (Calendar.SUNDAY == c.get(c.DAY_OF_WEEK)) {  
                 recvdDate = addDays(recvdDate, -2);     
                  date = new SimpleDateFormat("yyyy-MM-dd").format(recvdDate); 
                 } else if (isHoliday(recvdDate)) {      
                    recvdDate = addDays(recvdDate, -1); 
                   date = new SimpleDateFormat("yyyy-MM-dd").format(recvdDate); 
               } else {                  
                 date = currentDate;  
}          
                  list.add(date);            
}          
        if (i < 0) {              
         String preDate = list.get(-(i + 1));    
         Date recvdDate = addDays(new SimpleDateFormat("yyyy-MM-dd").parse(preDate), -1); 
               Calendar c = new GregorianCalendar();          
               c.setTime(recvdDate);                
         if (Calendar.SUNDAY == c.get(c.DAY_OF_WEEK)) {  
                 recvdDate = addDays(recvdDate, -2); 
                  date = new SimpleDateFormat("yyyy-MM-dd").format(recvdDate);  
             }
        else if (isHoliday(recvdDate)) {        
            Date recvdDate1 = addDays(recvdDate, -1);  
                 date = new SimpleDateFormat("yyyy-MM-dd") 
                           .format(recvdDate1);          
          } else {    
          date = new SimpleDateFormat("yyyy-MM-dd").format(recvdDate);             
          }              
         list.add(date);  
}        
       }        
         return list;  
​     }    
}

 

supporting methods used in this method are available in Q2 below.

Q. How to get the Date of  business day(excluding weekends & Holidays) some days after/before today in java ?

A. Given utility methods have been written for past(before) days. We can test it after applying any negative integer value for days parameter in public Date getTargetDate(int id,int days) method.

Similarly positive integer value can be used to get future dates.

public Date getTargetDate(int id,int days) throws ParseException{  
         Date targetDate = addDays(new Date(),days);          
       List hd= getHolidays();      
   int countHolidays=0;  

   for (int j = days; j <= 0; j++) {    
         Date rDate = addDays(new Date(), j);  
         String reDate=new SimpleDateFormat("yyyy-MM-dd").format(rDate);  
            for (int i = 0; i < hd.size(); i++) { 
               if(reDate.equalsIgnoreCase(hd.get(i))){  
                 countHolidays++;                  
   }              
   }                              
  Calendar c = Calendar.getInstance();  
       c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(reDate));      
          int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);              
  if(dayOfWeek ==1){                  
  countHolidays++;              
  }              
  if(dayOfWeek ==7){  
                  countHolidays++;     
      }          
​ }              
​    targetDate = addDays(targetDate , -countHolidays);                
  while (isHoliday(targetDate)) {          
   targetDate  = addDays(targetDate, -1);        
}                      
  return targetDate;    
}

 public static Date addDays(Date d, int days) {  
      Calendar cal = Calendar.getInstance();        
  cal.setTime(d);        
  cal.add(Calendar.DATE, days);      
   return cal.getTime();    
}

public static boolean isHoliday(java.util.Date d) {    
    Calendar c = new GregorianCalendar();    
​    c.setTime(d);      
   String recDate= new SimpleDateFormat("yyyy-MM-dd").format(d);  
      if((Calendar.SATURDAY == c.get(c.DAY_OF_WEEK)) || (Calendar.SUNDAY == c.get(c.DAY_OF_WEEK)) || getHolidays().contains(recDate.toString())) {
            return (true);        
  } else {          
  return false;      
  }    
​} 

Below in the getHolidays() method, we can put all holidays dates.

public static List getHolidays(){        
  List hd = new ArrayList();      
  hd.add("2013-12-25"); hd.add("2014-01-01"); hd.add("2014-01-20"); 
hd.add("2014-02-17"); hd.add("2014-0526"); hd.add("2014-07-04");  
hd.add("2014-09-01"); hd.add("2014-11-27"); hd.add("2014-11-28"); 
hd.add("2014-12-25"); hd.add("2014-12-26"); hd.add("2015-01-01");  
 return hd;  
}

 

Q. How to get number of business days(excluding weekends & holidays) between two dates in java ?

​A. Given utility methods has two parameters with start Date & end Date in Date format.

public static int getBusinessDaysBetweenTwoDates(Date startDate, Date endDate) throws ParseException {
         DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
         Calendar startCal;        
​  Calendar endCal;   
        startCal = Calendar.getInstance();  
         startCal.setTime(startDate);    
      endCal = Calendar.getInstance();
        endCal.setTime(endDate);              
  int workDays = 0;        
  //Return 0 if start and end are the same        
  if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
             return 0;          
​ }
  if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {
      startCal.setTime(endDate);   
      endCal.setTime(startDate);        
  }          
  do {
            startCal.add(Calendar.DATE, 1);   
            Date holiday = startCal.getTime(); 
            String holiDayDate= df.format(holiday);    
​        if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY && !(getHolidays().contains(holiDayDate.toString()))) {   
               ++workDays;            
  }          
 ​ } while (startCal.getTimeInMillis() < endCal.getTimeInMillis());      
    return workDays;      
​}

public static List getHolidays(){  
​ List hd = new ArrayList();  
hd.add("2013-12-25"); hd.add("2014-01-01"); hd.add("2014-01-20");
hd.add("2014-02-17"); hd.add("2014-0526"); hd.add("2014-07-04");  
hd.add("2014-09-01"); hd.add("2014-11-27"); hd.add("2014-11-28");  
hd.add("2014-12-25"); hd.add("2014-12-26"); hd.add("2015-01-01");          
 return hd;   ​
}

If start Date & end Date are in String convert them into Date as below.

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");     
Date startDate = df.parse(startDate);
Date endDate = df.parse(endDate);

 

Q. How to convert date from one format to another format  in java ?

​A. We can use below Utility method to get any Date format changed.

public String formatDate(String curFormat, String toFormat, String date) {       
 DateFormat currentFormat = new SimpleDateFormat(curFormat); 
       DateFormat changeToFormat = new SimpleDateFormat(toFormat); 
       String formattedDate = "";      
   try {            
  Date changedDate = currentFormat.parse(date); 
            formattedDate = changeToFormat.format(changedDate);    
      } catch (ParseException e) {
             e.printStackTrace();        
  }      
  return formattedDate;    
}

 

 

Q. How to convert current Date(in String form) in different time zone in java ?

​A. We can use below Utility method to get current Date in different time zone. Here we are taking example of converting current Date from IST to PST time zone.

public static String getTodaysDateInPST() { 
   Date today = new Date(); 

   //displaying this date on IST timezone        
 DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       df.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
       String IST = df.format(today);
       System.out.println("Date in Indian Timezone (IST) : " + IST);  
   
//dispalying date on PST timezone        
  df.setTimeZone(TimeZone.getTimeZone("PST"));  
       String PST = df.format(today);        
  System.out.println("Date in PST Timezone : " + PST);   
    return PST;    
}

 

 

Q. How to convert current Date(in java.util.Date form) in different time zone in java ?

​A. We can use below Utility method to get current Date in different time . Here we are taking example of converting current Date from IST to PST time zone. Return type of method will be java.util.Date this time.

public static Date getCurrentDateInPST() throws ParseException{
   Date today = new Date();
   DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
   DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   df.setTimeZone(TimeZone.getTimeZone("PST")); 
   String PST = df.format(today);        
  Date pst=df2.parse(PST);
  return pst;  
 }

 

 

Q. How to get date after/before some number of days in java ? How to add or subtract number of days in a particular date to get new date?

​A. We can use below Utility method to get required Date after adding or subtracting some number of days. Here we are taking example of addDays() method where we can pass a date & the number of days need to be added or subtracted. Negative value of days parameter will result in past date.

public static Date addDays(Date d, int days) { 
   Calendar cal = Calendar.getInstance(); 
   cal.setTime(d); 
   cal.add(Calendar.DATE, days); 
  return cal.getTime(); 
}

 

Q. How to get list of case-insensitive Strings ?  How to use contains – without case sensitivity?

​A.  We can have a requirement where we want to check if list contains some particular string or not . In that case we can use this method .

List<String> locations = new ArrayList<String>( );

locations.add("New Delhi");
locations.add("Mumbai");
locations.add("Kolkata");
locations.add("Chennai");

if(locations.contains("new delhi"))  // false
Set<String> locationsSet=  new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);

            locationsSet.addAll(locations);

if(locationsSet.contains("new delhi")) // true

Put all the items of List into a TreeSet as given above and then check.

2 thoughts on “Important Utility Methods

  1. You completed a few good points there. I did a search on the issue and found a good number of people will have the same opinion with your blog.

Leave a Reply


Top