Comparison between dates

Asked

Viewed 677 times

5

I am wanting to validate the inclusion of dates in my system, referring to the lot of products, but I believe I am a little hasty in the way I am doing.

For what I need, I thought of three situations I should control, which would be them:

The date of manufacture cannot be later/longer than the expiry date;

The expiration date cannot be earlier/shorter than the manufacturing date (it seems a redundant way to analyze the 1st validation);

The expiry date may not be less than the current date;

I made an example well simple and dry, only to illustrate, and so that errors in the comparison of dates can be pointed out.

  public class ValidaData extends JFrame {

    JLabel labelFab = new JLabel("Fabricação: ");
    CampoData fabricacao = new CampoData();

    JLabel labelVal = new JLabel("Validade: ");
    CampoData validade = new CampoData();

    JButton botao = new JButton("Calcular");

    public ValidaData() {
        setSize(500, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel painel = new JPanel();
        painel.setLayout(new FlowLayout());

        painel.add(labelFab);
        painel.add(fabricacao);

        painel.add(labelVal);
        painel.add(validade);

        painel.add(botao);
        botao.setPreferredSize(new Dimension(90, 20));
        botao();
        add(painel);
    }

    private void botao() {
        botao.addActionListener((ActionEvent e) -> {
            valida();
        });
    }

    Date dataAtual;

    private boolean valida() {
        if (fabricacao.getValor().compareTo(validade.getValor()) != 0) {
            JOptionPane.showMessageDialog(null, "A data de fabricação, não pode ser posterior a data de validade!");
            fabricacao.requestFocus();
            return false;
        } 
        
        else if (validade.getValor().compareTo(fabricacao.getValor()) != 0) {
            JOptionPane.showMessageDialog(null, "A data de validade, não pode ser anterior a data de fabricação!");
            validade.requestFocus();
            return false;
        }
        
        else if (validade.getValor().compareTo(dataAtual = new Date()) != 0) {
            JOptionPane.showMessageDialog(null, "A data de validade esta vencida !");
            validade.requestFocus();
            return false;

        } else {
            JOptionPane.showMessageDialog(null, "Deu certo !!");
            return true;
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(()
                -> {
            ValidaData e = new ValidaData();
            e.setVisible(true);
        });
    }
}

class CampoData extends JFormattedTextField {

    private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    public CampoData() {
        setColumns(6);
        try {
            MaskFormatter mf = new MaskFormatter("##/##/####");
            mf.install(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setValor(Object valor) {
        setText(sdf.format((Date) valor));
    }

    public Date getValor() {
        try {
            SimpleDateFormat sdft = new SimpleDateFormat("dd/MM/yyyy");
            return sdft.parse(getText());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Não foi possível obter a data!");
            e.printStackTrace();
            return null;
        }
    }
}

1 answer

4


Use the methods after and before class util.Date to compare dates instead of compareTo:

private boolean valida() {
    if (fabricacao.getValor().after(validade.getValor())) {
        JOptionPane.showMessageDialog(null, "A data de fabricação, não pode ser posterior a data de validade!");
        fabricacao.requestFocus();
        return false;
    } 

    else if (validade.getValor().before(fabricacao.getValor())) {
        JOptionPane.showMessageDialog(null, "A data de validade, não pode ser anterior a data de fabricação!");
        validade.requestFocus();
        return false;
    }

    else if (validade.getValor().before(dataAtual = new Date())) {
        JOptionPane.showMessageDialog(null, "A data de validade esta vencida !");
        validade.requestFocus();
        return false;

    } else {
        JOptionPane.showMessageDialog(null, "Deu certo !!");
        return true;
    }
}

I recommend you read this answer regarding the new java date API, how and why to migrate to it.

  • Just one question, in case you exchange the Formatted textField for another component, like that Jdatechooser, the validation may not be correct ? I did a test, and even formatting it, it picks up the date like this: Sat Sep 02 15:19:54 BRT 2017. But in his "viewer", he shows me a dd/MM/yyyy, in this case after and before may not be suitable ?

  • @Gustavosantos did not understand your doubt. The changes I made in the code do not take into account where the data comes from, only that the dates are of type util.Date. You can switch to the component you want on your screen (or even use in text mode), as long as ensures that the values compared in the valida() are of the type mentioned. I would suggest until passing the values of manufacture and validity by parameter to this method.

Browser other questions tagged

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