quarta-feira, 29 de abril de 2009

Calculando diferença entre datas

Hoje coloco aqui disponível a todos um exemplo de classe que utilizo para calcular diferença entre datas




package com.wealthsystems.sim.utils.date;

import java.util.Date;

/**
* Calculate difference of dates
*
* @author Clayton
*
*/
public class DateDiff {
/**
* Get difference in milliseconds
*
* @param data1
* data mais antiga (natal)
* @param data2
* data mais nova (ano novo)
* @return
*/
public static long inMiliseconds(Date data1, Date data2) {
long diffMillis = data2.getTime() - data1.getTime();
return diffMillis;
}

/**
* Get difference in seconds
*
* @param data1
* @param data2
* @return
*/
public static long inSeconds(Date data1, Date data2) {
long diffSecs = inMiliseconds(data1, data2) / (1000); // 604800
return diffSecs;
}

/**
* Get difference in minutes
*
* @param data1
* @param data2
* @return
*/
public static long inMinutes(Date data1, Date data2) {
long diffMins = inMiliseconds(data1, data2) / (60 * 1000); // 10080
return diffMins;
}

/**
* Get difference in hours
*
* @param data1
* @param data2
* @return
*/
public static long inHours(Date data1, Date data2) {
long diffHours = inMiliseconds(data1, data2) / (60 * 60 * 1000); // 168
return diffHours;
}

/**
* Get difference in days
*
* @param data1
* @param data2
* @return
*/
public static long inDays(Date data1, Date data2) {
long diffDays = inMiliseconds(data1, data2) / (24 * 60 * 60 * 1000); // 7
return diffDays;
}

public static String toStringInHour(Date data1, Date data2) {
long hour = DateDiff.inHours(data1, data2);
long minutes = DateDiff.inMinutes(data1, data2);
long seconds = DateDiff.inSeconds(data1, data2);

StringBuffer sb = new StringBuffer();
sb.append(hour);
sb.append(":");
sb.append(minutes - (hour * 60));
sb.append(":");
sb.append(seconds - (minutes * 60));

return sb.toString();
}
}