如何获得当前日期并显示在GUI组件中显示

解决方案 »

  1.   


    /*
     * 以下代码在 Windows XP + JDK 5 测试通过,2008年11月14日,oracle_lover
     */
    import java.awt.BorderLayout;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;public class DateTest extends JFrame {  private static final long serialVersionUID = 2535740494585478304L;  public DateTest() {
        super("Date Test");    this.setSize(640, 480); // 设置窗口大小
        this.setLocationRelativeTo(null); // 窗口屏幕居中
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 窗口关闭,则程序退出
        java.awt.Container container = this.getContentPane();    // 获取当前日期和时间
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime();
        // 用不同方式格式化日期
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年M月d日");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss.ms");
        String strDate1 = sdf1.format(now);
        String strDate2 = sdf2.format(now);
        String strDate3 = sdf3.format(now);
        String strDate4 = now.toLocaleString();
        String strDate5 = now.toGMTString();
        String strDate6 = now.toString();    // 创建一个文本框显示各种不同格式的日期
        JTextArea taDate = new JTextArea();
        JScrollPane sp = new JScrollPane(taDate);
        taDate.append(strDate1 + "\n");
        taDate.append(strDate2 + "\n");
        taDate.append(strDate3 + "\n");
        taDate.append(strDate4 + "\n");
        taDate.append(strDate5 + "\n");
        taDate.append(strDate6);    container.add(sp, BorderLayout.CENTER);
      }  // 创建GUI
      private static void createAndShowGUI() {
        DateTest xframe = new DateTest();
        xframe.setVisible(true);
      }  public static void main(String[] args) {
        // 为事件处理线程安排一个任务:创建并显示程序的GUI
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
      }}
      

  2.   

    楼上的得到日期太麻烦,给你个简单的,格式可以自己配置:
    String date = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(Calendar.getInstance().getTime());
    格式配置我想大家一看就懂,就不多说了!得到字符串了,显示到GUI任何组建都不是问题了吧!