From what I understand, you need to display the duration of a period in format String
. If so, test the following:
1) Insert the getDescricaoDuracao()
in XHTML:
<p:outputText value="#{horasBean.hora.getDescricaoDuracao()}" />
2) In the entity hora
, insert the methods below:
(If you’re 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’re 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;
}