The program below is the answer to Liang’s Introduction to Java Programming (9th Edition) Chapter 2 Exercise 2.8.
Question: (Current time) Listing 2.6, 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.
1 2 |
/**<br /> *<br /> * @Author: Aghatise Osazuwa<br /> * Website: www.cscprogrammingtutorials.com<br /> *<br /> * Exercise 2.8 - Current Time<br /> *<br /> */ <br /><br />import java.util.Scanner;<br /><br />public class CurrentTime {<br /> public static void main (String [] args) {<br /><br /> Scanner input = new Scanner(System.in);<br /><br /> System.out.println("This Program Displays The Time In The Specified Time Zone.n");<br /> <br /> // Obtain the total milliseconds since midnight, Jan 1, 1970<br /> long totalMilliseconds = System.currentTimeMillis();<br /><br /> // Obtain the total seconds since midnight, Jan 1, 1970<br /> long totalSeconds = totalMilliseconds / 1000;<br /><br /> // Compute the current second in the minute in the hour<br /> long currentSecond = totalSeconds % 60;<br /><br /> // Obtain the total minutes<br /> long totalMinutes = totalSeconds / 60;<br /><br /> // Compute the current minute in the hour<br /> long currentMinute = totalMinutes % 60;<br /><br /> // Obtain the total hours<br /> long totalHours = totalMinutes / 60;<br /><br /> // Compute the current hour<br /> long currentHour = totalHours % 24;<br /> <br /> System.out.println("Enter the time zone offset to GMT:" );<br /><br /> int timeZoneOffset = input.nextInt();<br /> currentHour = currentHour + timeZoneOffset;<br /><br /> if (currentHour >= 24){<br /> currentHour = currentHour - 24;<br /> } else if (currentHour == 0){<br /> currentHour = 24 + timeZoneOffset;<br /> }<br /><br /> // Display results<br /> System.out.println("Current time is " + currentHour + ":"<br /> + currentMinute + ":" + currentSecond + " GMT " + timeZoneOffset + ".n");<br /> }<br />}<br /> |
Click here to see other solutions to Introduction to Java Programming.