user412308 user412308 - 20 days ago 5
Java Question

Java - Adding a 0 in the minutes of the current time (GMT)

when I output the following code (taken from dr. Liang Introduction to Java, 10th ed., chapter 03 - selections)

/*
(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();
}
}


the output is

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


How can I let display instead
11:02:31?


Thank you.

Answer

You can do something like this,

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

I have just converted the minutes variable to string and then checked whether the length of the string is 1 that is whether it is a one digit minute and then i have appended the existing minutes to 0 and then you can display it as before like this,

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