Java黑皮书课后题第2章:*2.8(当前时间)程序清单2-7给出了显示当前格林尼治时间的程序。修改这个程序,提示用户输入相对于GMT的时区偏移量,显示在这个特定时区的时间
*2.8(当前时间)程序清单2-7给出了显示当前格林尼治时间的程序。修改这个程序,提示用户输入相对于GMT的时区偏移量,显示在这个特定时区的时间
- 题目
- 题目描述
- 运行示例
- 程序清单2-7(非本题代码)+思路(注释)
- 代码块
题目
题目描述
*2.8(当前时间)程序清单2-7给出了显示当前格林尼治时间的程序。修改这个程序,提示用户输入相对于GMT的时区偏移量,显示在这个特定时区的时间
运行示例
Enter the time zone offset to GMT: -5
The current time is 4:50:34
程序清单2-7(非本题代码)+思路(注释)
public class ShowCurrentTime {public static void main(String[] args) {// 2.8可以在这里获取时区// Obtain the total milliseconds since midnight, Jan 1, 1970long totalMilliseconds = System.currentTimeMillis();// Obtain the total seconds since midnight, Jan 1, 1970long totalSeconds = totalMilliseconds / 1000;//2.8可以在这里将求出的秒数+时区和GMT时区的偏移(秒数)// Compute the current second in the minute in the hourlong currentSecond = totalSeconds % 60;// Obtain the total minuteslong totalMinutes = totalSeconds / 60;// Compute the current minute in the hourlong currentMinute = totalMinutes % 60;// Obtain the total hourslong totalHours = totalMinutes / 60;// Compute the current hourlong currentHour = totalHours % 24;// Display resultsSystem.out.println("Current time is " + currentHour + ":"+ currentMinute + ":" + currentSecond + " GMT");}
}
代码块
import java.util.Scanner;public class Test2_8 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter the time zone offset to GMT:");int offset = input.nextInt();// Obtain the total milliseconds since midnight, Jan 1, 1970long totalMilliseconds = System.currentTimeMillis();// Obtain the total seconds since midnight, Jan 1, 1970long totalSeconds = totalMilliseconds / 1000;totalSeconds += offset * 60 * 60;// Compute the current second in the minute in the hourlong currentSecond = totalSeconds % 60;// Obtain the total minuteslong totalMinutes = totalSeconds / 60;// Compute the current minute in the hourlong currentMinute = totalMinutes % 60;// Obtain the total hourslong totalHours = totalMinutes / 60;// Compute the current hourlong currentHour = totalHours % 24;// Display resultsSystem.out.println("Current time is " + currentHour + ":"+ currentMinute + ":" + currentSecond + " GMT");}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
