基于帖子计算日期之间的天数差异
如何为向量 vE 和 vS 提供随机日期,然后返回日期之间的差异?回想一下 vS 必须大于 vE 吗?实际上,我应该分成两种方法:随机日期和其他计算差异。
/*
* Randomizacao
*/
package random04DiferencaDataVetor;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class Random04DiferencaDataVetor {
public static void main(String[] args) throws ParseException {
final long intervalo = 1000000000;
Random rnd = new Random();
String[] vE = new String[5];
String[] vS = new String[5];
for (int i = 0; i < vE.length; i++) {
/*
* arrumar vetores para gerar datas aleatorias
* lembrando que vS deve ser maior que vE
*/
retornaData();
}
}
static void retornaData() throws ParseException {
final long intervalo = 1000000000;
Random rnd = new Random();
// formatando as datas
DateFormat formato = new SimpleDateFormat("yyyy");
Date anoE = formato.parse("2012");
long timeE = anoE.getTime();
Date anoS = formato.parse("2013");
long timeS = anoS.getTime();
// define o intervalo de datas em 1 ano
long tempoIntervalo = timeE - timeS;
// randomiza a data de entrada
long rndTempoE = timeE + (long) (rnd.nextDouble() * tempoIntervalo);
// data entrada
String dataE = new SimpleDateFormat("hh:mm dd/MM/yyyy").format(rndTempoE);
// randomiza a data de saida
long rndTempoS = rndTempoE + (long) (rnd.nextDouble() * intervalo * 2);
// data de saida
String dataS = new SimpleDateFormat("hh:mm dd/MM/yyyy").format(rndTempoS);
// formato de data
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/MM/yyyy");
try {
Date dataEnt = sdf.parse(dataE);
Date dataSaida = sdf.parse(dataS);
long differenceMilliSeconds = dataSaida.getTime() - dataEnt.getTime();
long days = differenceMilliSeconds / 1000 / 60 / 60 / 24;
long hours = (differenceMilliSeconds % (1000 * 60 * 60 * 24)) / 1000 / 60 / 60;
long minutes = (differenceMilliSeconds % (1000 * 60 * 60)) / 1000 / 60;
System.out.println(days + " days, " + hours + " hours, " + minutes + " minutes.");
} catch (ParseException e) {
e.printStackTrace();
}
}
}