Pessoal, estou estudando Java. Estava olhando configurações de data e hora. Até o momento entendi que é mais ou menos assim:
packagetestesdecoisas;importjava.util.Date;publicclassTestesDeCoisas{publicstaticvoidmain(String[]args){//Exibição de data e horaDateteste=newDate();System.out.println("A data é "+teste);}}
A minha dúvida é: Quando eu executo esse código a resposta seria “A data é Wed Aug 23 18:40:29 BRT 2017”
Como faço para formatar isso? Colocando por exemplo 23/08/2017 ou até mesmo conseguir separar isso em algo como “Hoje é 23/08/27 e são 18:40” ?
Então, aproveitando o tópico. Agradeço ao amigo @rodevops pela indicação. Não sabia por onde começar e agora consegui. A pergunta agora é: Como faço para passar isso pra uma Swing? O action do botão fica assim:
Alguém poderia me explicar como fazer isso dar certo?
rodevops1 like
Você não formata o texto da data/hora…
horario.format(relogio.toString());
Formata a data/hora…
horario.format(relogio);
RSM_RLB
Opa. Deu certo aqui! Muito obrigado mano. Só uma ultima pergunta pra fechar: Quando eu seto o “SimpleDateFormat horario = new SimpleDateFormat(“HH:mm:ss”)” ele me dá a hora estática. Ex: 20:44:58
Sabe se tem alguma forma de fazer esse contador continuar andando sem precisar ter que clicar no botão novamente para atualizar os segundos?
PauloRAA
Testa isso ae, aqui deu certo:
packagebr.paulo;importjava.util.Calendar;importjava.util.GregorianCalendar;publicclasstesteextendsjavax.swing.JFrame{/** * Creates new form Frame */publicteste(){initComponents();newThread(){@Overridepublicvoidrun(){for(;;){dataEHora();try{sleep(1000);}catch(InterruptedExceptionie){ie.printStackTrace();}}}}.start();}/** * 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">privatevoidinitComponents(){lData=newjavax.swing.JLabel();lHora=newjavax.swing.JLabel();setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);lData.setFont(newjava.awt.Font("Tahoma",0,24));// NOI18NlData.setForeground(newjava.awt.Color(51,51,255));lData.setText("jLabel1");lHora.setFont(newjava.awt.Font("Tahoma",0,24));// NOI18NlHora.setForeground(newjava.awt.Color(51,51,255));lHora.setText("jLabel2");javax.swing.GroupLayoutlayout=newjavax.swing.GroupLayout(getContentPane());getContentPane().setLayout(layout);layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(lData).addGap(18,18,18).addComponent(lHora).addContainerGap(220,Short.MAX_VALUE)));layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(lData).addComponent(lHora)).addContainerGap(260,Short.MAX_VALUE)));pack();}// </editor-fold>/** * @param args the command line arguments */publicvoiddataEHora(){Calendarcal=newGregorianCalendar();intdia=cal.get(Calendar.DAY_OF_MONTH);intmes=cal.get(Calendar.MONTH);intano=cal.get(Calendar.YEAR);inthora=cal.get(Calendar.HOUR);intminuto=cal.get(Calendar.MINUTE);intsegundo=cal.get(Calendar.SECOND);lData.setText("Data:"+dia+"/"+(mes+1)+"/"+ano);lHora.setText("Hora:"+hora+":"+minuto+":"+segundo);}publicstaticvoidmain(Stringargs[]){/* Set the Nimbus look and feel *///<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */try{for(javax.swing.UIManager.LookAndFeelInfoinfo:javax.swing.UIManager.getInstalledLookAndFeels()){if("Nimbus".equals(info.getName())){javax.swing.UIManager.setLookAndFeel(info.getClassName());break;}}}catch(ClassNotFoundExceptionex){java.util.logging.Logger.getLogger(teste.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}catch(InstantiationExceptionex){java.util.logging.Logger.getLogger(teste.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}catch(IllegalAccessExceptionex){java.util.logging.Logger.getLogger(teste.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}catch(javax.swing.UnsupportedLookAndFeelExceptionex){java.util.logging.Logger.getLogger(teste.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}//</editor-fold>/* Create and display the form */java.awt.EventQueue.invokeLater(newRunnable(){publicvoidrun(){newteste().setVisible(true);}});}// Variables declaration - do not modifyprivatejavax.swing.JLabellData;privatejavax.swing.JLabellHora;// End of variables declaration}