Conversion of Dates to Mysql database

Asked

Viewed 5,783 times

5

Hello!

Well, I’m using xhtml and primefaces.

On my xhtml page, I have a field for date and use the converter to save in the database, I have a problem with the day.

If I want to save 30/04/1989

In the saved database 1989/04/29

My field is Date type.

public class Funcionario {
    private Long id;
    private String nomeUsuario;
    private String senha;
    private String nome;
    private String cpf;
    private Date data;
    private Cargo funcao = new Cargo();
    private Restricao restricao = new Restricao();

    //getters e setters omitidos
}

Any date is always recorded with a day less.

On my xhtml page I am using a jsf converter.

<p:outputLabel for="data" value="Nascimento" />
    <p:inputMask id="data" mask="99/99/9999" placeholder="Dia/Mês/Ano"
     value="#{BeanFuncionario.funcionario.data}"
     requiredMessage="Campo data de nascimente é obrigatório."
     required="true">

       <f:converter converterId="javax.faces.DateTime" />
   </p:inputMask>

However, I did an insertion test using a class with junit and I note that:

   @Test
public void salvar(){

    CargoDAO cargo = new CargoDAO();
    RestricaoDAO restricao = new RestricaoDAO();

    //Cargos e retricoes
    List<Cargo> lista = cargo.listar();
    List<Restricao> lista2 = restricao.listar();


    //CRIA UM USUARIO
    Funcionario usuario = new Funcionario();
    usuario.setNomeUsuario("jhimmyliborio");
    usuario.setSenha("s2mm1s");
    usuario.setNome("TESTE DE INCLUSAO 1");
    usuario.setCpf("88888888888");

    // DEFININDO DATA
    Date data = new Date("1989/04/30");
    usuario.setData(data);

    //DEFINE FUNCAO E RESTRICAO
    usuario.setFuncao(lista.get(1));
    usuario.setRestricao(lista2.get(1));

    // SALVAR
    FuncionarioDAO udao = new FuncionarioDAO();
    udao.salvar(usuario);
}

If I use Date to set the date, everything goes well. inserir a descrição da imagem aqui

If I use Calendar to set the date, I end up having problems with the month. it is incremented +1;

30/04/1989 - >> 1989/05/30

    @Test
public void salvar(){


    CargoDAO cargo = new CargoDAO();
    RestricaoDAO restricao = new RestricaoDAO();

    //Cargos e retricoes
    List<Cargo> lista = cargo.listar();
    List<Restricao> lista2 = restricao.listar();


    //CRIA UM USUARIO
    Funcionario usuario = new Funcionario();
    usuario.setNomeUsuario("liborioJhimmy");
    usuario.setSenha("s2mm1s");
    usuario.setNome("TESTE DE INCLUSAO 2");
    usuario.setCpf("99999999999");

    // DEFININDO DATA
    Calendar c = Calendar.getInstance();
    c.set(1989, 04, 30);
    Date data = c.getTime();
    usuario.setData(data);

    //DEFINE FUNCAO E RESTRICAO
    usuario.setFuncao(lista.get(1));
    usuario.setRestricao(lista2.get(1));

    // SALVAR
    FuncionarioDAO udao = new FuncionarioDAO();
    udao.salvar(usuario);
}

inserir a descrição da imagem aqui

This is my DAO.

   public void salvar(Funcionario user) {
    StringBuilder sql = new StringBuilder();
    sql.append(" INSERT INTO funcionario ");
    sql.append("(nome_usuario, senha, nome, cpf, nascimento, cargo_id) ");
    sql.append("VALUES (lower(?),lower(?),lower(?),lower(?), ?,lower(?)) ");

    try (Connection conexao = new Conexao().getConexao()) {
        PreparedStatement pstm = conexao.prepareStatement(sql.toString());
        pstm.setString(1, user.getNomeUsuario());
        pstm.setString(2, user.getSenha());
        pstm.setString(3, user.getNome());
        pstm.setString(4, user.getCpf());
        pstm.setDate(5, new Date(user.getData().getTime()));
        pstm.setLong(6, user.getFuncao().getId());

        pstm.executeUpdate();
        //Mensagens.msgSucesso("Novo usuário salvo", user.getNomeUsuario());
        pstm.close();
    } catch (SQLException e) {
        e.printStackTrace();
        Mensagens.msgErro("Erro", e.getMessage().toString());
    }

I don’t know how the jsf converter behaves, I have already created my class prorpia that converts the input from the user page to the bank. But it gives a conversion error. Unable to convert a String to Date.

    public static void dataBanco(Funcionario funcionario){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    String banco = sdf.format(funcionario.getData());
    Date data;
    try {
        data = sdf.parse(banco);
        funcionario.setData(data);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

Can someone help me?

  • Could you define your question better? I see several questions.

1 answer

5


You report two problems: one with the date using primeface components (which is innocent in this particular case because this behavior is JSF itself) and one using the class Calendar.

Date problem in JSF

The JSF tries to convert the reported time to GMT. The time zone of Brasilia is GMT-3. That is, the JSF is decreasing 3 hours from the informed date, 30/04/1989 (midnight), resulting in the day before.

You can inform the time zone desired (GMT-3) for the date converter. In your code, it would look like this:

<p:inputMask id="data" mask="99/99/9999" placeholder="Dia/Mês/Ano"
     value="#{BeanFuncionario.funcionario.data}"
     requiredMessage="Campo data de nascimente é obrigatório."
     required="true">

    <f:convertDateTime pattern="dd/MM/yyyy" timeZone="GMT-3"/>
</p:inputMask>

Or you can configure your application so that JSF always uses the local GMT of the system (file web xml.):

<context-param>
    <param-name>
            javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE
    </param-name>
    <param-value>true</param-value>
</context-param>

Date issue considering multiple time zones in JSF

The first solution I presented above applies if your system is only used in Brail, and the second solution applies well if your system is used in one country only (regardless of which).

If your system needs to be shared by users in different time zones, and depending on the need, you may have to do a more complex treatment of date and time, such as letting JSF convert the date to GMT and saving the user’s GMT as well. But the ideal solution will depend on your requirements.

Date problem using Calendar class

The method set of an object Calendar expects the month to be indexed to zero (as it is...). So this code:

Calendar c = Calendar.getInstance();
c.set(1989, 04, 30);
Date data = c.getTime();
System.out.println(data.toString());

Produces the following output:

Tue May 30 10:27:33 BRT 1989

That is, May 30 and not April 30 as you expect.

You would have to set 3 for April. Or use class constants Calendar:

c.set(1989, Calendar.APRIL, 30);

  • So I would have to take the String typed by the user there in xhtml. Convert to date and manipulate with Calendar and shorten the month, that’s it?

  • @user3096136 I updated my answer to also address the date problem in JSF; that seems to be the main problem while the Calendar problem seems to be just an investigation.

  • Very well explained Caffé, Thanks for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.