Difereça entre LocalDateTime exibir Duração hora : min

Gostaria de no campo duração usar horas : minutos, 01:10 (1 hora e 10 min) Utilizo Java 8

A página de exibição:
<?xml version="1.0" encoding="ISO-8859-1" ?>

<ui:composition template="layout.xhtml">
   
	
	<ui:define name="conteudo">
			<h1>Relatório de Entradas e Saídas</h1>
		<h:panelGroup rendered="#{!facesContext.messageList.isEmpty()}" >
		<div id="infoMessage">
			<h:messages/>
		</div>
		</h:panelGroup>
		<br />
			
			<form jsf:id="form">
			<fieldset>
				<legend>Parâmetros de entradas e saídas</legend>
				
				<label for="Matrícula">Matrícula</label><br />
				<input type="text" jsf:value="#{relatorioEntradaSaidaBean.matricula}" id="id" /><br />
				
				<label for="dataInicial">Data Inicial</label><br />
				<input type="date" jsf:value="#{relatorioEntradaSaidaBean.dataInicial}" id="dataInicia" >
					<f:convertDateTime type="localDate" pattern="yyyy-MM-dd" />
				</input ><br />
				<label for="dataFinal">Data Final</label><br />
				<input type="date" jsf:value="#{relatorioEntradaSaidaBean.dataFinal}" id="dataFinal" >	
					<f:convertDateTime type="localDate" pattern="yyyy-MM-dd" />
				</input ><br />				
					
			</fieldset>
			<input type="submit" value="gerar relatorio" jsf:action="#{relatorioEntradaSaidaBean.gerarRelatorio}" /><br />
			
			<h:panelGroup rendered="#{not empty relatorioEntradaSaidaBean.acessos}" >
			<table>
				<tr>
					<th>Matrícula</th>
					<th>Nome</th>
					<th>Entrada</th>
					<th>Saída</th>
					<th>Duração</th>					
				</tr>	
				<ui:repeat var="a" value="#{relatorioEntradaSaidaBean.acessos}">
					<tr>
						<td>#{a.aluno.matricula}</td>
						<td>#{a.aluno.nome}</td>
						<td>
							<h:outputText values="#{a.entrada}" >  
								<f:convertDateTime type="LocaldateTime" pattern="dd/MM/yyyy HH:mm" /> 
							</h:outputText>						
						</td>
						<td>
							<h:outputText values="#{a.saida}" >  
								<f:convertDateTime type="LocaldateTime" pattern="dd/MM/yyyy HH:mm" /> 
							</h:outputText>						
						</td>						
						<td> ???</td>			
					</tr>	
				</ui:repeat>				
			</table>
			</h:panelGroup>
		</form>

		</ui:define>
</ui:composition>

</html>

Método Calcular está nesta classe, uso Java 8:

package br.com.softblue.loucademia.domain.acesso;

import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import br.com.softblue.loucademia.domain.aluno.Aluno;

@Entity
@Table(name = "ENTRADAS_SAIDAS")
public class Acesso implements Serializable{
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "ID", nullable = false)
	private Integer id;
	
	@ManyToOne
	@JoinColumn(name = "ALUNO_ID", nullable = false)
	private Aluno aluno;
	
	@Column(name = "ENTRADA", nullable = false)
	private LocalDateTime entrada;
	
	@Column(name = "SAIDA", nullable = true)
	private LocalDateTime saida;
	
	// Identifica se entrada e saida estão preenchidas
	public boolean isEntradaSaidaPreenchidas() {
	// retorna verdadeiro se entrada e saída estão preenchidas
		if(entrada != null && saida != null) {
			return true;
		}
		return false;		
	}
	
	// colocar data e hora do sistema nos registros de entrada ou saida
	public TipoAcesso registrarAcesso() {
		LocalDateTime now = LocalDateTime.now();
		
		TipoAcesso tipoAcesso;
		
		// se não tem 1 entrada cadastrada
		// então aluno ainda não entrou, então é um registro de entrada
		if(entrada==null) {
			entrada = now;
			tipoAcesso = TipoAcesso.Entrada;
		}else if(saida==null) {
			saida = now;
			tipoAcesso = TipoAcesso.Saida;
		}else {
			tipoAcesso = null;
		}
		
		return tipoAcesso;
	}
	
	public String calcularDuracao() {
		// metodo feito no formato para mostrar na tela
		if(entrada==null || saida==null) {
			return null;
		}
		
		// Duration para determinarintervalo de tempo
		Duration d = Duration.between(entrada, saida);
		
		
		
	
		return ;
		
		
		
		
	}
	
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Aluno getAluno() {
		return aluno;
	}
	public void setAluno(Aluno aluno) {
		this.aluno = aluno;
	}
	public LocalDateTime getEntrada() {
		return entrada;
	}
	public void setEntrada(LocalDateTime entrada) {
		this.entrada = entrada;
	}
	public LocalDateTime getSaida() {
		return saida;
	}
	public void setSaida(LocalDateTime saida) {
		this.saida = saida;
	}
	
	
	@Override
	public String toString() {
		return "Acesso [id=" + id + ", aluno=" + aluno + ", entrada=" + entrada + ", saida=" + saida + "]";
	}
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Acesso other = (Acesso) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
	
	
	

}

Método especifico de calcular duração:
No Java 11

public String calcularDuracao() {
		if (entrada == null || saida == null) {
			return null;
		}
		
		Duration d = Duration.between(entrada, saida);
		return String.format("%02d:%02d", d.toHoursPart(), d.toMinutesPart());
	}

Gostaria no Java 8:

    public String calcularDuracao() {
		// metodo feito no formato para mostrar na tela
		if(entrada==null || saida==null) {
			return null;
		}
		
		// Duration para determinarintervalo de tempo
		Duration d = Duration.between(entrada, saida);
		
		
		
		
		return null;
		
		
		
		
	}

Tentei isso mas não Funcionou:

public String calcularDuracao() {
		// metodo feito no formato para mostrar na tela
		if(entrada==null || saida==null) {
			return null;
		}
		
		// Duration para determinarintervalo de tempo
		Duration d = Duration.between(entrada, saida);
		
	    
		
		
		long hours = d.toHours();
		int minutes = (int) ((d.getSeconds() % (60 * 60)) / 60);
		int seconds = (int) (d.getSeconds() % 60);
	    		
		return String.format("%02d:%02d", hours, minutes);
		
		
		
		
	}

Bom dia amigo.

Segue um método que utilizo:

/**
 * Este método calcula a duração entre dois horários
 *
 * @param entrada LocalDateTime com valor inicial
 * @param saida LocalDateTime com valor final
 * @return String com duração formatada HH:mm
 */
public String calcularDuracao(LocalDateTime entrada, LocalDateTime saida) {
    try {
        Duration drt = Duration.between(entrada, saida);
        LocalTime lt = LocalTime.ofNanoOfDay(drt.toNanos());
        return lt.format(DateTimeFormatter.ofPattern("HH:mm"));
    } catch (Exception ex) {
        ex.printStackTrace();
        return "";
    }
}

Boa sorte, abraços. :metal::sunglasses::metal:

2 curtidas

Dependendo da versão que você estiver utilizando, você pode seguir por abordagens diferentes

JSF 2.2: você pode criar um converter de LocalDateTime para Date e então utilizar o f:convertDateTime para formatar a saída

JSF 2.3: Nesta versão foi incluído suporte a LocalDate, LocalDateTime, LocalTime, OffsetTime OffsetDateTime e ZonedDateTime

<h:outputText value="#{meuBean.meuLocalDateTime}">
  <f:convertDateTime type="localDateTime" pattern="HH:mm"/>
</h:outputText>
1 curtida