Change a date from yyyy-MM-dd to dd-mm-yyyy

6

I have dataTable where I display some data but the date is coming in yyyy-mm-dd format how do I change the format of this date so that I can display it correctly in my dataTable ? And where do I do this formatting? In Bean or DAO?

Here is my method that takes the data from the database and fills in dataTable :

@PostConstruct
    public void listar(){
        try{
            TarefaDAO tarefaDAO = new TarefaDAO();
            listaTarefa = tarefaDAO.listarPorUsuario(usuarioBean.getUsuarioLogado());   
        }catch(RuntimeException e){

        }
    }

DAO:

@SuppressWarnings("unchecked")
    public List<Tarefa> listarPorUsuario(Usuario usuario) {
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        List<Tarefa> lista = null;
        try {
            Query consulta = sessao.getNamedQuery("Tarefa.listarPorCodigo");
            consulta.setParameter("usuario", usuario);
            lista = consulta.list();

        } catch (RuntimeException ex) {
            throw ex;
        } finally {
            sessao.close();
        }
        System.out.println("LISTA NO DAO:" + lista);
        return lista;
    }

Declaration of variables that are dates in the Model:

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "data_inicio", nullable = false)
    private Date dataInicio;


    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "data_fim", nullable = false)
    private Date dataFim;

I want to display the date in dd-mm-yyyy format

    
asked by anonymous 14.07.2015 / 14:03

3 answers

6

Use DateFormat

SimpleDateFormat formatoDesejado = new SimpleDateFormat("dd/MM/yyyy");

String dataFormatada = null;

dataFormatada = formatoDesejado.format("sua data hora");

If you need to convert use .parse within .format()

EDIT: adding other examples to form @ jsantos1991 Examples

EDIT: Convert String to Date, using the template I quoted above.

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dataString = dataFormatada //  <= sua data no formato de String; 

Date date = formatter.parse(dataString);
    
14.07.2015 / 14:13
9

If you want another alternative, you can use <f:convertDateTime/> within outputText that is in dataTable

Example:

<p:column headerText="Data">
    <h:outputText value="#{var.data}">
        <f:convertDateTime pattern="dd/MM/yyyy HH:mm"/>
    </h:outputText>
</p:column>
    
14.07.2015 / 15:06
0

It worked for me.

minhaTextView.setText(new SimpleDateFormat("dd/MM/yyyy HH:mm")
             .format(meuObjeto.getDate()));

where "dd / MM / yyyy HH: mm" is the format I want and

"myObject.getDate ()" is the date I currently have.

    
19.09.2016 / 21:45