Dates Conversion to the Mysql database

4

Hello!

Well, I'm using xhtml and primefaces.

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

If I want to save 04/30/1989

In the database saved 1989/04/29

My field is of type Date.

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 one day less.

In my xhtml page I'm 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 some test insertion using a class with jUnit and I noticed 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 happens fine.

IfIuseCalendartosetthedate,Ienduphavingprobelmaswiththemonth.itisincremented+1;

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

@Testpublicvoidsalvar(){CargoDAOcargo=newCargoDAO();RestricaoDAOrestricao=newRestricaoDAO();//CargoseretricoesList<Cargo>lista=cargo.listar();List<Restricao>lista2=restricao.listar();//CRIAUMUSUARIOFuncionariousuario=newFuncionario();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);
}

ThisismyDAO.

publicvoidsalvar(Funcionariouser){StringBuildersql=newStringBuilder();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 do not know how the jsf converter behaves, I've already created my prorpia class that converts the user's page entry to the bank. But it's a conversion error. Could not 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 anyone help me?

    
asked by anonymous 02.11.2014 / 17:20

1 answer

5

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

Problem with date in JSF

JSF attempts to convert the reported time to GMT . The time zone of Brasília is GMT-3 . That is, the JSF is decreasing 3 hours from the reported date, 30/04/1989 (midnight), resulting in the previous day.

You can enter the desired time zone (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 system GMT ( web.xml file ):

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

Problem with date 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 a country only (regardless of which).

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

Problem with date using the Calendar class

The set method of an object Calendar expects the month to be indexed to zero (because 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 to April. Or use the constants of class Calendar :

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

    
03.11.2014 / 13:28