【问题标题】:Date and Time Format in JavaJava中的日期和时间格式
【发布时间】:2013-02-06 06:24:22
【问题描述】:

我有这个代码:

class ClockLabel extends JLabel implements ActionListener {

    public ClockLabel() {
        super("" + new java.util.Date());
       Timer t = new Timer(1000, this);
       t.start();
    }

   @Override
   public void actionPerformed(ActionEvent ae) {
      txtclock.setText((new java.util.Date()).toString());
   }
 }

我的输出是

Wed Feb 06 14:22:44 CST 2013

如何以这种格式更改我的输出

"MM dd yyyy HH:mm:ss"

【问题讨论】:

  • 我尝试输入 super("" + new java.util.Date("MM dd yyyy HH:mm:ss"));
  • 谷歌搜索java format dateSimpleDateFormat 作为第一个链接。

标签: java datetime


【解决方案1】:

您可以使用SimpleDateFormat 格式化日期

SimpleDateFormat f = new SimpleDateFormat("MM dd yyyy HH:mm:ss");
txtclock.setText(f.format(new java.util.Date()));

【讨论】:

    【解决方案2】:

    查看SimpleDateFormat 类。可以构造SimpleDateformat with patteryn"MM dd yyyy HH:mm:ss"and pass the date object informat()`的实例。

    【讨论】:

      【解决方案3】:
      SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy HH:mm:ss");
      String sDate= sdf.format(new java.util.Date());
      

      【讨论】:

        【解决方案4】:

        使用simple date format

        @Override
           public void actionPerformed(ActionEvent ae) {
              SimpleDateFormat format = new SimpleDateFormat("MM dd yyyy HH:mm:ss");
              txtclock.setText(format.format(new java.util.Date()));
           }
        

        【讨论】:

          【解决方案5】:

          修改你的代码为

          class ClockLabel extends JLabel implements ActionListener {
              java.util.Date date;
              public ClockLabel() {
                  super(getStrVAl());
                  Timer t = new Timer(1000, this);
                  t.start();
              }
          
              @Override
              public void actionPerformed(ActionEvent ae) {
                  txtclock.setText(getStrVAl());
              }
          
              public String getStrVAl() {
                  date=new java.util.Date();
                  String val=date.getMonth().toString()+" "+date.getDate().toString()+" "+date.getYear().toString()+" "date.getHours().toString()+":"+date.getMinutes().toString()+":"+date.getSeconds()().toString()+" ");
                  return val;
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-09-25
            • 1970-01-01
            • 2016-11-24
            • 1970-01-01
            相关资源
            最近更新 更多