2016-05-05 7 views
0

私は、Javaスイングウィンドウで使用するカウントアップタイマー関数を作成しました。問題は時間がゼロから数え始めないことです。私がタイマーを始めるとき、最初の時間は常に1時間先に来る。ここで0から開始しないjavaのタイマーをカウントする

は私のコードです:

public static void timeRecording(){ 
     Date startTime = new Date(); 
      int delay = 1000; //milliseconds 
      ActionListener taskPerformer = new ActionListener() { 
       public void actionPerformed(ActionEvent evt) { 
         SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss"); 
         Date actualTime = new Date(); 
         String dateToPrint = timeFormat.format(new Date(actualTime.getTime() - startTime.getTime())); 


         //String dateToPrint = timeFormat.format(actualTime); 
         System.out.println(actualTime); 
         //actualTime 
         // String timeToPrint.timeFormat = actualTime; 
         timerLabel.setText(dateToPrint); 

       } 
      }; 
    new Timer(delay, taskPerformer).start(); 

} 

これは、開始時に示された時間である:new Date(actualTime.getTime() - startTime.getTime())で日付を作成します。 Time shown at start

+3

午前/午後でKアワー(0-11)

を使用して試みることができます。 – assylias

+0

@assylias おそらく私のタイムゾーンはUTC + 0(リスボングリニッジ)です。私はすでにtimeFormat.setTimeZone(TimeZone.getTimeZone( "GMT"))でフォーマットを変更しようとしましたが、今は12:00:00から開始します – Bruno

+0

リスボンはUTC + 1にあります – assylias

答えて

0

"hh:mm:ss"のごSimpleDateFormatJavaDocにと記載され、h使用しています:午前/午後に

h時間(1-12

をこのようにあなたの時間は常に開始します1

あなたのタイムゾーンはUTC + 1であるので、あなたはすなわち、おそらく"KK:mm:ss"

+0

これは機能します! 「HH」も同様に機能します。 – Bruno

0

どうなりますが、日付の差が1秒であれば、これはということです1970年1月1日00:01 UTCに第1

ただし、フォーマットするとき、DateFormatはタイムゾーン(リスボン= UTC + 1)を使用し、1970年1月1日1時01分(UTC + 1)に日付を表​​示します。

あなたは正しい出力を取得したい場合は、フォーマッタのタイムゾーンを設定する必要があります。

SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss"); 
fmt.setTimeZone(TimeZone.getTimeZone("UTC")); 
System.out.println(fmt.format(new Date(0))); //outputs 00:00:00 as expected 

注:正しいフォーマットパターンがHH(0-23)で、1でないHH( -12)。

関連する問題