2016-11-18 10 views
2

ときに私のコード次の出力(JavaへのDR梁はじめ、10編から取られた、第03章 - 。。選択)のJava - 現在の時刻(GMT)の分で0を追加

/* 
(Current time) Listing 2.7, ShowCurrentTime.java, gives a program that displays 
the current time in GMT. Revise the program so that it prompts the user to enter 
the time zone offset to GMT and displays the time in the specified time zone. 
*/ 


import java.util.Scanner; 

public class Ex_03_08 { 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 

     System.out.print("Enter the time zone (GMT): "); 
     int gmt = input.nextInt(); 

     long totalMilliseconds = System.currentTimeMillis(); 

     long totalSeconds = totalMilliseconds/1000; 

     long currentSecond = totalSeconds % 60; 

     long totalMinutes = totalSeconds/60; 

     long currentMinute = totalMinutes % 60; 

     long totalHours = totalMinutes/60; 

     long currentHour = totalHours % 24; 
     currentHour = currentHour + gmt; 

     System.out.println("The current time is " + currentHour + ":" 
       + currentMinute + ":" + currentSecond); 

     input.close(); 
    } 
} 

出力は

Enter the time zone (GMT): 1 
The current time is 11:2:31 

でどのように私は、ディスプレイの代わりに11:02:31?

ありがとうせることができます。

答えて

3

あなたはこのような何かを行うことができ、

String currentMinuteStr=""+currentMinute ; 
if(currentMinuteStr.length()==1){ 
currentMinuteStr="0"+currentMinuteStr; 
} 

私は単なる文字列に変数分を変換して、文字列の長さは、それが1桁の分であるかどうかである1であるか否かを確認してからきた私0に既存の分を追加していると、あなたはあなたがformatメソッドを使用してCスタイルのprintfに、あなたの入力をフォーマットすることができ

System.out.println("The current time is " + currentHour + ":" 
      + currentMinuteStr+ ":" + currentSecond); 
1

、前と同じように、このようにそれを表示することができます。

class NumericFormat 
{ 
    public static void main(String[] args) { 
     System.out.format("%02d%n",3); 
     //you can use \n too but %n is preferrable for format method 
    } 
} 

リンクに障害が発生した場合は、ここで、Java Docs

でより良い理解を得るフォーマッタのいくつかはあります。サイドノートでは

Java Docs Formatters


、日付と時刻をフォーマットして使用するには、Javaの8はきれい作り付けのAPIを持っています。このOracleチュートリアルをご覧ください - Date Time Parsing and Formatting

0
 long totalMilliseconds = System.currentTimeMillis(); 

    long totalSeconds = totalMilliseconds/1000; 

    long currentSecond = totalSeconds % 60; 

    long totalMinutes = totalSeconds/60; 

    long currentMinute = totalMinutes % 60; 

    long totalHours = totalMinutes/60; 

    long currentHour = totalHours % 24; 
    currentHour = currentHour + gmt; 

    String strTime = "" + (currentHour < 10 ? "0" + currentHour : currentHour) + 
     (currentMinute < 10 ? "0" + currentMinute : currentMinute) + 
     (currentSecond < 10 ? "0" + currentSecond : currentSecond); 

    System.out.println("The current time is : " + strTime); 
関連する問題