【问题标题】:How to convert seconds of Timer to hh:mm:ss?如何将 Timer 的秒数转换为 hh:mm:ss?
【发布时间】:2013-10-12 21:50:00
【问题描述】:

如果两次问同一个问题被视为垃圾邮件,我真的很抱歉,因为我在一小时前已经问过倒计时。

但现在它的新问题是虽然我无法再次引起任何人对这个问题的关注。感谢你们,我已经成功地编写了计时器,但后来我尝试将秒转换为 hh:mm:ss 格式,但它没有用。而不是一直持续到 00:00:00。它只是显示我编码它的时间,仅此而已。

这是我的代码。

import java.util.Timer;
import java.util.TimerTask;
public class countdown extends javax.swing.JFrame {


public countdown() {
    initComponents();
    Timer timer;

    timer = new Timer();
    timer.schedule(new DisplayCountdown(), 0, 1000);
}

class DisplayCountdown extends TimerTask {

      int seconds = 5;
      int hr = (int)(seconds/3600);
      int rem = (int)(seconds%3600);
      int mn = rem/60;
      int sec = rem%60;
      String hrStr = (hr<10 ? "0" : "")+hr;
      String mnStr = (mn<10 ? "0" : "")+mn;
      String secStr = (sec<10 ? "0" : "")+sec; 

      public void run() {
           if (seconds > 0) {
              lab.setText(hrStr+ " : "+mnStr+ " : "+secStr+"");
              seconds--;
           } else {

              lab.setText("Countdown finished");
              System.exit(0);
          }    
    }
}     
public static void main(String args[]) {
    new countdown().setVisible(true);
}  

【问题讨论】:

  • 这是众包编程吗?
  • int seconds = 5; int hr = (int)(seconds/3600); ?你预计小时是多少?尝试先在本站搜索答案:how to convert milliseconds to hhmmss-format
  • 没有。我正在创建一个完整的软件,而计时器只是其中的一部分,由于我是 Java 语言的初学者,所以我不太了解它。
  • hr 是小时。我希望它根据我给出的秒数进行转换。现在我只给 5 秒,但在最终软件中我必须让它 3600 秒,因此 1 小时。
  • lab.setText(hrStr+ " : "+mnStr+ " : "+secStr+""); 在 while 循环中,您不会使用 seconds-- 更新小时、分钟;我已将一个页面链接到我的评论。尝试使用该解决方案来格式化时间。

标签: java timer


【解决方案1】:

移动你的计算

  int hr = seconds/3600;
  int rem = seconds%3600;
  int mn = rem/60;
  int sec = rem%60;
  String hrStr = (hr<10 ? "0" : "")+hr;
  String mnStr = (mn<10 ? "0" : "")+mn;
  String secStr = (sec<10 ? "0" : "")+sec; 

进入run 方法。

【讨论】:

  • 对 'int' 的两次强制转换是多余的,可以删除。
【解决方案2】:
public String getCountDownStringInMinutes(int timeInSeconds)
{
    return getTwoDecimalsValue(timeInSeconds/3600) + ":" + getTwoDecimalsValue(timeInSeconds/60) + ":" +     getTwoDecimalsValue(timeInSeconds%60);
}


public static String getTwoDecimalsValue(int value)
{
    if(value>=0 && value<=9)
    {
        return "0"+value;           
    }
    else
    {
        return value+"";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2012-02-20
    • 1970-01-01
    • 2011-10-30
    相关资源
    最近更新 更多