As I understand it, you need to display the length of a period in String
format. If so, try the following:
1) Insert getDescricaoDuracao()
into XHTML:
<p:outputText value="#{horasBean.hora.getDescricaoDuracao()}" />
2) In the hora
ed entity, insert the methods below:
(If you are using LocalDateTime
)
public LocalDateTime getHoraInicial() {
return horaInicial;
}
public LocalDateTime getHoraFinal() {
return horaFinal;
}
public Duration calcularDuracao(LocalDateTime inicio, LocalDateTime fim) {
return Duration.between(toInstant(inicio), toInstant(fim));
}
public Instant toInstant(LocalDateTime t) {
return t.atZone(ZoneId.systemDefault()).toInstant();
}
(Or if you are using Date
)
public Date getHoraInicial() {
return horaInicial;
}
public Date getHoraFinal() {
return horaFinal;
}
public Duration calcularDuracao(Date inicio, Date fim) {
return Duration.between(toInstant(inicio), toInstant(fim));
}
public Instant toInstant(Date d) {
return Instant.ofEpochMilli(d.getTime());
}
Common methods between LocalDateTime
or Date
:
public String getDescricaoDuracao() {
return toString(calcularDuracao(getHoraInicial(), getHoraFinal()));
}
public String toString(Duration duracao) {
String retorno = "";
if (duracao != null) {
String dia = "", hora = "", minuto = "";
Long tDia = (long) 0, tHora = (long) 0, tMinuto = (long) 0;
Map<TimeUnit,Long> i = dividirDuracao(duracao.toMillis());
tDia = i.get(TimeUnit.DAYS);
tHora = i.get(TimeUnit.HOURS);
tMinuto = i.get(TimeUnit.MINUTES);
dia = tDia + " d";
hora = tHora + " h";
minuto = tMinuto + " min";
if (tDia > 0) {
retorno = dia + " " + hora + " " + minuto;
} else {
if (tHora > 0) {
retorno = hora + " " + minuto;
} else {
if (tMinuto > 0) {
retorno = minuto;
} else {
retorno = "-";
}
}
}
} else {
retorno = "-";
}
return retorno;
}
public Map<TimeUnit,Long> dividirDuracao(Long intervalo) {
List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));
Collections.reverse(units);
Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();
long milliesRest = intervalo;
for ( TimeUnit unit : units ) {
if (milliesRest > 0) {
long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
long diffInMilliesForUnit = unit.toMillis(diff);
milliesRest = milliesRest - diffInMilliesForUnit;
result.put(unit,diff);
} else {
result.put(unit,(long) 0);
}
}
return result;
}