Date Format[RESOLVIDO]

10 respostas
juliocesarsrosa

Galera gostaria de saber se alguem tem algum algoritimo que por exemplo : o usuario vai entrar com uma data em um campo do tipo data dd/mm/aaaa
quando ele começar a digitar a data vai sendo formatada sem que nescessite que ele digite as “/” espero ter sido claro Obrigado !

10 Respostas

javer

É você não foi muito claro não, primeiramente, como aqui é Java Avançado e não fala sobre o ambiente, nos diga: é Desktop ou Web?

GuilhermeKFreitas

No caso do “campo”, você quer dizer tipo um JTextField ?

Talvez você deva procurar pelo MaskFormatter.
Tem um pessoal que não gosta muito dele, e prefere optar pelo DocumentFilter.

Os dois formatam o campo, conforme você quer.
Dá uma pesquisada .
Aqui mesmo no GUJ tem vários post sobre eles.

[Edit]
Opa, é verdade… tem que ver pra qual ambiente é também…

Kanin_Dragon

Se vc estiver falando de Web, utilize javascript para formatar o campo em quanto o usuário digita, é a melhor maneira!

juliocesarsrosa

Desculpem esqueci de especificar é JSE preciso apenas que quando o usuario digitar uma data em um Textfield ela seja formatada dessa forma
dd/mm/aaaa sem que seja necessario que ele digite a “/” . Obrigado

javer
Vou de passar de "graça" um PlainDocument que faz isso, coloca ele no seu JTextField e pronto.
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class DateDocument extends PlainDocument {

    private static int TAMANHO_TEXTO = 10; //para o formato dd/MM/yyyy
    private static String CARACTERES_DATA = "[telefone removido]/";
    private static String FORMATO = "dd/MM/yyyy";

    public DateDocument() {
    }

    public void setDate(Date date) {
        String strr = date == null ? "" : new java.text.SimpleDateFormat(FORMATO).format(date);
        try {
            remove(0, getLength());
            super.insertString(0, strr, null);
        } catch (BadLocationException ex) {
            Logger.getLogger(DateDocument.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        //Nao mostrar se a string for null.
        if (str == null) {
            return;
        }

        //Verificar o tamanho maximo permitido
        if (getLength() > TAMANHO_TEXTO) {
            return;
        }

        //Somente para validar os caracteres digitados
        for (int i = 0; i < str.length(); i++) {
            if (CARACTERES_DATA.indexOf(String.valueOf(str.charAt(i))) == -1) {
                java.awt.Toolkit.getDefaultToolkit().beep();
                return;
            }
        }

        //Checar a posicao do caracter que separa a data
        if ((offset == 2) || (offset == 5)) {
            if (!str.equals("/")) {
                return;
            }
        }

        super.insertString(offset, str, attr);
        // inserir o caracter que separa
        if ((offset == 1) || (offset == 4)) {
            super.insertString(offset + 1, "/", attr);
        }

        //If the user has finished entering validate the date entered by him.
        if (offset == TAMANHO_TEXTO - 1) {
            String strr = getText(0, getLength());
            remove(0, getLength());
            super.insertString(0, getCorrectDate(strr), attr);
        }
    }

    private String getCorrectDate(String oldDate) {
        String newDate = "";
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(FORMATO);
        try {
            java.util.Date date1 = formatter.parse(oldDate);
            newDate = formatter.format(date1);
        } catch (java.text.ParseException ex) {
            Logger.getLogger(DateDocument.class.getName()).log(Level.SEVERE, null, ex);
            newDate = "";
        }
        return newDate;
    }

    public Date getDate() {
        Date newDate = null;
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(FORMATO);
        try {
            newDate = formatter.parse(this.getText(0, TAMANHO_TEXTO));
        } catch (java.text.ParseException ex) {
            //Logger.getLogger(DateDocument.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadLocationException ex) {
            //Logger.getLogger(DateDocument.class.getName()).log(Level.SEVERE, null, ex);
        }
        return newDate;
    }
}
juliocesarsrosa

Eu axei esse codigo em outro topico tbm muito obrigado mesmo assim. !

juliocesarsrosa

Galera testei essa classe e ela esta dando a Exception StackOverflowError algm sabe o que pode ser???

juliocesarsrosa

Estou chamando a classe no Focus Ganed do meu textfield como ja uso para outras formações no caso de valores
monetarios mas para data nao esta funcionando sera que é a classe ou o modo como estou chamando ??

txDataEmissao.setDocument(new DateDocument());

Obrigado

juliocesarsrosa

Ja consegui arrumar galera vlw Obrigado

uhitlei1
javer:
Vou de passar de "graça" um PlainDocument que faz isso, coloca ele no seu JTextField e pronto.
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class DateDocument extends PlainDocument {

    private static int TAMANHO_TEXTO = 10; //para o formato dd/MM/yyyy
    private static String CARACTERES_DATA = "[telefone removido]/";
    private static String FORMATO = "dd/MM/yyyy";

    public DateDocument() {
    }

    public void setDate(Date date) {
        String strr = date == null ? "" : new java.text.SimpleDateFormat(FORMATO).format(date);
        try {
            remove(0, getLength());
            super.insertString(0, strr, null);
        } catch (BadLocationException ex) {
            Logger.getLogger(DateDocument.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        //Nao mostrar se a string for null.
        if (str == null) {
            return;
        }

        //Verificar o tamanho maximo permitido
        if (getLength() > TAMANHO_TEXTO) {
            return;
        }

        //Somente para validar os caracteres digitados
        for (int i = 0; i < str.length(); i++) {
            if (CARACTERES_DATA.indexOf(String.valueOf(str.charAt(i))) == -1) {
                java.awt.Toolkit.getDefaultToolkit().beep();
                return;
            }
        }

        //Checar a posicao do caracter que separa a data
        if ((offset == 2) || (offset == 5)) {
            if (!str.equals("/")) {
                return;
            }
        }

        super.insertString(offset, str, attr);
        // inserir o caracter que separa
        if ((offset == 1) || (offset == 4)) {
            super.insertString(offset + 1, "/", attr);
        }

        //If the user has finished entering validate the date entered by him.
        if (offset == TAMANHO_TEXTO - 1) {
            String strr = getText(0, getLength());
            remove(0, getLength());
            super.insertString(0, getCorrectDate(strr), attr);
        }
    }

    private String getCorrectDate(String oldDate) {
        String newDate = "";
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(FORMATO);
        try {
            java.util.Date date1 = formatter.parse(oldDate);
            newDate = formatter.format(date1);
        } catch (java.text.ParseException ex) {
            Logger.getLogger(DateDocument.class.getName()).log(Level.SEVERE, null, ex);
            newDate = "";
        }
        return newDate;
    }

    public Date getDate() {
        Date newDate = null;
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(FORMATO);
        try {
            newDate = formatter.parse(this.getText(0, TAMANHO_TEXTO));
        } catch (java.text.ParseException ex) {
            //Logger.getLogger(DateDocument.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadLocationException ex) {
            //Logger.getLogger(DateDocument.class.getName()).log(Level.SEVERE, null, ex);
        }
        return newDate;
    }
}

Muito bom esse código,
vc teria algum para Monetário? (0,00)

Criado 2 de fevereiro de 2011
Ultima resposta 3 de jun. de 2012
Respostas 10
Participantes 5