【问题标题】:hello world. this is my stopwatch class. return the value in seconds你好世界。这是我的秒表课。以秒为单位返回值
【发布时间】:2013-10-25 01:40:22
【问题描述】:

这是我的秒表课。我的问题是,我怎样才能将它转换为秒,以便它在几秒钟内给我输出?在此先感谢

public class StopWatch

{  
   /**
      Constructs a stopwatch that is in the stopped state
      and has no time accumulated.
   */
   public StopWatch()

   {  

 reset();

   }

   /**
      Starts the stopwatch. Time starts accumulating now.
   */
   public void start()

   {  

      if (isRunning) return;

      isRunning = true;

      startTime = System.currentTimeMillis();

   }

   /**
      Stops the stopwatch. Time stops accumulating and is
      is added to the elapsed time.
   */
   public void stop()

   {  

      if (!isRunning) return;

      isRunning = false;

      long endTime = System.currentTimeMillis();

      elapsedTime = elapsedTime + endTime - startTime;

   }

   /**
      Returns the total elapsed time.
      @return the total elapsed time
   */
   public long getElapsedTime()

   {  

      if (isRunning) 

      {  

         long endTime = System.currentTimeMillis();

         return elapsedTime + endTime - startTime;

      }

      else

         return elapsedTime;

   }

   /**
      Stops the watch and resets the elapsed time to 0.
   */
   public void reset()

   {  

      elapsedTime = 0;

      isRunning = false;

   }

   private long elapsedTime;

   private long startTime;

   private boolean isRunning;

}

【问题讨论】:

  • 请问您是问如何将毫秒转换为秒?

标签: java stopwatch


【解决方案1】:

您可以使用TimeUnit 枚举轻松转换时间单位。只需使用convert 方法即可

//lets see how many seconds are in 1234 milliseconds 
System.out.println(TimeUnit.SECONDS.convert(1234, TimeUnit.MILLISECONDS));
//output: 1

【讨论】:

    【解决方案2】:

    使用 Google Guava 库 com.google.common.base.Stopwatch 类,无需重新发明轮子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2021-01-02
      • 1970-01-01
      • 2022-01-27
      • 2011-08-02
      • 2018-01-30
      相关资源
      最近更新 更多