The problem Write a program that displays the current time in GMT. Prompt the user to enter the time zone offset to GMT and displays the time in the specified time zone. Here is a examples run:
Enter the time zone offset to GMT: -5
The current time is 4:50:34
Breaking it down private final static String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z" ;
public static void main ( String [] Strings ) {
Scanner input = new Scanner ( System . in );
System . out . print ( "Enter the time zone offset to GMT: " );
int timeZoneChange = input . nextInt ();
input . close ();
String timeZoneAdjustment = timeZoneChange > 0 ? "+" : "-" ;
final SimpleDateFormat sdf = new SimpleDateFormat ( DATE_FORMAT );
sdf . setTimeZone ( TimeZone . getTimeZone ( "GMT" + timeZoneAdjustment
- String . valueOf ( timeZoneChange )));
String dateTimeString = sdf . format ( new Date ());
System . out . println ( "Current date time is " + dateTimeString );
}
Output Enter the time zone offset to GMT: 0
Current date time is Tue, 05 Apr 2016 02:05:29 GMT-00:00
Enter the time zone offset to GMT: 3
Current date time is Tue, 05 Apr 2016 05:05:51 GMT+03:00
Current time GMT offset posted by Justin Musgrove on 04 April 2016
Tagged: java, java-exercises-beginner, intro-to-java-10th-edition, and ch2
Share on: Facebook Google+