Friday, November 6, 2015

// // Leave a Comment

Java Program To Display Current Time In GMT

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.

/**
 *
 * @Author: Aghatise Osazuwa
 * Website: www.cscprogrammingtutorials.com
 *
 * Exercise 2.8 - Current Time
 *
 */ 

import java.util.Scanner;

public class CurrentTime {
    public static void main (String [] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("This Program Displays The Time In The Specified Time Zone.\n");
        
        // Obtain the total milliseconds since midnight, Jan 1, 1970
        long totalMilliseconds = System.currentTimeMillis();

        // Obtain the total seconds since midnight, Jan 1, 1970
        long totalSeconds = totalMilliseconds / 1000;

        // Compute the current second in the minute in the hour
        long currentSecond = totalSeconds % 60;

        // Obtain the total minutes
        long totalMinutes = totalSeconds / 60;

        // Compute the current minute in the hour
        long currentMinute = totalMinutes % 60;

        // Obtain the total hours
        long totalHours = totalMinutes / 60;

        // Compute the current hour
        long currentHour = totalHours % 24;
        
        System.out.println("Enter the time zone offset to GMT:" );

        int timeZoneOffset = input.nextInt();
        currentHour = currentHour + timeZoneOffset;

        if (currentHour >= 24){
            currentHour = currentHour - 24;
        } else if (currentHour == 0){
            currentHour = 24 + timeZoneOffset;
        }

        // Display results
        System.out.println("Current time is " + currentHour + ":"
                + currentMinute + ":" + currentSecond + " GMT " + timeZoneOffset + ".\n");
    }
}

Click here to see other solutions to Introduction to Java Programming.

0 comments:

Post a Comment


DISCLAIMER: Opinions expressed in comments are those of the comment writers alone and does not reflect or represent the views of the post author. We reserve the right to delete any post deemed inappropriate or offensive and/or spammy. Please do not use abusive words/hate speech.

I Appreciate your valuable Feedback. So, Please DO NOT SPAM - Spam comments will be deleted immediately.

Don't use brand name in name field and you're not allowed to use links in comments unless it's necessary. Such comments will be removed immediately.

Thanks.