Thursday, April 9, 2015

Find number of sundays between two dates

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.text.ParseException;

public class HelloWorld{

     public static void main(String []args){
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        Date fromDate = null;
        Date toDate = null;
        int totalDays = 0;
        int noSundays = 0;

        try {
            fromDate = sdf.parse("18/04/2015");
            toDate = sdf.parse("09/05/2015");
            Calendar cal = Calendar.getInstance();
            cal.setTime(toDate);
            cal.add(Calendar.DATE, 1);
            toDate = cal.getTime();
            totalDays = (int)( (toDate.getTime() - fromDate.getTime())
                    / (24 * 60 * 60 * 1000));
           
            cal.setTime(fromDate);
            int fromDay = cal.get(Calendar.DAY_OF_WEEK);
           
            int firstWeekDays = 7 - fromDay+1;
            if(totalDays <= firstWeekDays)
                noSundays = 0;
            else{
                int remainingDays = totalDays - firstWeekDays;
                noSundays = (int)Math.floor(remainingDays/7);
                if((remainingDays%7) !=0)
                    noSundays++;
            }
           
            if(fromDay==1)
                noSundays++;
           
        System.out.println("Sundays:"+noSundays);
        } catch (ParseException e) {
            System.out.println("Parsing Exception on date");
        }
       
     }
}

Sunday, December 28, 2014

Reading properties file in webapp

Description: place your properties file in src/main/resources. After packaging in war or jar it appears under WEB-INF/classes/ directory

code:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ReadPropertyValues
{
    private static Logger logger=LogManager.getLogger(ReadPropertyValues.class.getName());
    public static Properties getPropertyValues()
    {
        Properties prop = new Properties();
        try
        {
            // load a properties file
            InputStream i=ReadPropertyValues.class.getClassLoader().getResourceAsStream("config.properties");
            if(i==null)
                throw new IOException("file not found");
            prop.load(i);

        } catch (IOException ex)
        {
            logger.error("Error while reading the property file: ", ex);
        }
        return prop;
    }

}