Wednesday, October 8, 2014

Utilities

Index :

  • GetDayWeek from Date (Get the day or week from the date passed)
  • GetDaysDiff (Calculating the difference between two dates)
  • parseCellDataToString (Reading the excel cell value irrespective of cellType)

---------------------------------------------------------------------------------------------------------------------

Gets the Day or the Week from the given date

public static String getDayWeek(String sourceDate, String opType) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
if ("WEEK".equalsIgnoreCase(opType)) {
String week = new SimpleDateFormat("w").format(sdf
.parse(sourceDate));
return week;
} else if ("DAY".equalsIgnoreCase(opType)) {
String day = new SimpleDateFormat("dd-MMM").format(sdf
.parse(sourceDate));
return day;
} else
return "";
} catch (Exception e) {
return "";
}
}

Usage :

getDayWeek("10/10/2014","DAY")

----------------------------------------------------------------------------------------------------------

Gets the difference in days between two days

public static int getDaysDiff(java.util.Date startDate,
java.util.Date endDate) {
long dateDiff = startDate.getTime() - endDate.getTime();
return (int) (dateDiff / (1000 * 60 * 60 * 24));

}

----------------------------------------------------------------------------------------------------------

 public static String parseCellDataToString(Cell cell){
    String cellStr;
int cellType= cell.getCellType();
        if(cellType==Cell.CELL_TYPE_STRING){
            // Return as it is since it is already in string format unless its date type  
            cellStr = cell.getStringCellValue();
        }
        else if(cellType==Cell.CELL_TYPE_NUMERIC || cellType==Cell.CELL_TYPE_FORMULA){
            // Remove any fractional data by parsing to long and then parse to string and return
            cellStr = String.valueOf((long)(cell.getNumericCellValue()));
        }
        else if(cellType==Cell.CELL_TYPE_BOOLEAN){
            cellStr = String.valueOf(cell.getBooleanCellValue());
        }
        else if(cellType==Cell.CELL_TYPE_BLANK){
        cellStr = "";
        }
        else{
        cellStr = "";
        }
        cellStr = cellStr.trim();
        return cellStr;

    }

No comments:

Post a Comment