[RESOLVIDO]Problema com Data, não sei o que ocorre!

7 respostas
D

Olá pessoal!! Estou usando o NachoCalendar, componente DateField (objeto dateField1). Estou primeiro fazendo um teste para saber como funciona para poder implementá-lo no meu sistema.

Sabem quando a pessoa "empaca" e não resolve o problema?? Então eu to assim há horas... pesquiso e nada... mudo e nada.... to ficando :shock: louca....

O fato é: pegando o valor do dataField1 este vem assim: Tue Oct 12 00:00:00 BRT 2010.
Para que apareça no nosso padrão fiz conforme mostra a linha 2 e 3 do código abaixo. Com isso a minha String ficou: 12/10/2010.
Mas eu na verdade não o quero como String, mas sim como Date. Portanto eu escrevi a linha 7, mas o meu objeto Date volta a ter o valor: Tue Oct 12 00:00:00 BRT 2010.

Eu já fiz esse procedimento milhares de vezes transformar String em Date e nunca "empaquei" como desta vez... não sei o que ocorre!
Segue o meu código:

private void dateField1StateChanged(javax.swing.event.ChangeEvent evt) {    
    DateFormat dfe = DateFormat.getDateInstance(DateFormat.MEDIUM);
    String dataTexto = dfe.format(dateField1.getValue());
    JOptionPane.showMessageDialog(this, "A data escolhida foi: " + dataTexto, "Data alterada", JOptionPane.INFORMATION_MESSAGE);
    Date d = new Date();
        try {
            d = dfe.parse(dataTexto);
        } catch (ParseException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

    System.out.print(d);

    }

Agradeço desde já qualquer ajuda.
Até mais,
Dina

7 Respostas

Guilherme_Reda

tente private DateFormat dfe = new SimpleDateFormat ("HH:mm:ss");

private void dateField1StateChanged(javax.swing.event.ChangeEvent evt) {      
DateFormat dfe = new SimpleDateFormat ("HH:mm:ss");
String dataTexto = dfe.format(dateField1.getValue());  
JOptionPane.showMessageDialog(this, "A data escolhida foi: " + dataTexto, "Data alterada", JOptionPane.INFORMATION_MESSAGE);  
Date d = new Date();  
    try {  
        d = dfe.parse(dataTexto);  
    } catch (ParseException ex) {  
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);  
    }  
  
System.out.print(d);  
      
}

não sei se o codigo inteiro ficaria assim mas DateFormat dfe = new SimpleDateFormat ("HH:mm:ss"); funciona pra mim

tkx

Boa noite Dina,
Dê uma olhada em SimpleDateFormat!
Acredito que resolverá seu problema!

SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy"); System.out.println(formato.format(d));

Guilherme_Reda
Guilherme Reda:
tente private DateFormat dfe = new SimpleDateFormat ("dd/MM/yyyy");
private void dateField1StateChanged(javax.swing.event.ChangeEvent evt) {      
DateFormat dfe = new SimpleDateFormat ("dd/MM/yyyy");
String dataTexto = dfe.format(dateField1.getValue());  
JOptionPane.showMessageDialog(this, "A data escolhida foi: " + dataTexto, "Data alterada", JOptionPane.INFORMATION_MESSAGE);  
Date d = new Date();  
    try {  
        d = dfe.parse(dataTexto);  
    } catch (ParseException ex) {  
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);  
    }  
  
System.out.print(d);  
      
}

não sei se o codigo inteiro ficaria assim mas DateFormat dfe = new SimpleDateFormat ("dd/MM/yyyy"); funciona pra mim

Desculpa, eu coloquei como horario
arrumado pra data

D

Olá pessoal, primeiramente, muito obrigada pelas respostas, mas infelizmente não funcionou. Isso que está me deixando louca, pois deveria funcionar! hehe

Segue a minha classe inteira com as modificações sugeridas…
Há mais alguma idéia do que pode ser???
Obrigada!!

public class NewJFrame extends javax.swing.JFrame {

    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
        //Define como será mostrada a data no componente dateField1
        dateField1.setDateFormat(DateFormat.getDateInstance(DateFormat.MEDIUM));
        dateField1.getDateFormat().setLenient(true);



    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        datePanel1 = new net.sf.nachocalendar.components.DatePanel();
        dateField1 = new net.sf.nachocalendar.components.DateField();

        FormListener formListener = new FormListener();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        dateField1.addChangeListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(170, Short.MAX_VALUE)
                .addComponent(datePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(98, 98, 98)
                .addComponent(dateField1, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(179, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(dateField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, Short.MAX_VALUE)
                .addComponent(datePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33))
        );

        pack();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements javax.swing.event.ChangeListener {
        FormListener() {}
        public void stateChanged(javax.swing.event.ChangeEvent evt) {
            if (evt.getSource() == dateField1) {
                NewJFrame.this.dateField1StateChanged(evt);
            }
        }
    }// </editor-fold>

    private void dateField1StateChanged(javax.swing.event.ChangeEvent evt) {
    
    
        DateFormat dfe = new SimpleDateFormat ("dd/MM/yyyy");
        String dataTexto = dfe.format(dateField1.getValue());
        JOptionPane.showMessageDialog(this, "A data escolhida foi: " + dataTexto, "Data alterada", JOptionPane.INFORMATION_MESSAGE);
        Date d = new Date();
            try {
                d = dfe.parse(dataTexto);
            } catch (ParseException ex) {
                Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }

        System.out.print(d);

    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });

    }

    // Variables declaration - do not modify
    private net.sf.nachocalendar.components.DateField dateField1;
    private net.sf.nachocalendar.components.DatePanel datePanel1;
    // End of variables declaration

}
tkx

Como assim não funcionou?
Testei aqui e está OK!

Vc diz por causa do que está sendo impresso no System.out.print?
Date eh um objeto que guarda mtas infos… qd vc coloca pura no sout, ele usa automaticamente o toString() do Date, que padroniza este formato!
Voce tem 3 saídas para isso:
1 - usar o SimpleDateFormat
2 - Criar sua classe Date customizada, sobrescrevendo o toString para imprimir do jeito que vc quer
3 - Criar uma função que receba um date e imprima um string formatado como vc quer!

tente no system.out.print colocar dfe.format(d) e veja o que ocorre!

D

tkx :oops: :oops: :oops:
Eu não acreditoooo!!
Funcionou!!!
Isso mesmo que vc falou!!!
Primeira vez que me deparo com isso…!! Quebrei a cabeça…!

Muito obrigada!! :slight_smile:

tkx

Por nada!

Edite o título e coloque um [RESOLVIDO] no início! =D

Criado 25 de outubro de 2010
Ultima resposta 25 de out. de 2010
Respostas 7
Participantes 3