下面是一个运行示例:
Enter the time zone offset to GMT(输入到格林尼的时区偏移量): -5
The current time is 4: 50: 34(时区偏移量是4h50m34s)
2-7显示当前时间
提示:可以通过调用 Systm.currentTimeMIllis( ) 返回当前时间。
1)调用 Systm.currentTimeMIllis( ) 方法获取1970年1月1日午夜到现在的毫秒数(例如:28毫秒),并且存放在变量 totalMilliseconds 中。
2)通过将毫秒数 totalMilliseconds 除以 1000 得到总毫秒数 totalseconds (例如:28毫秒 / 1000 = )。
3)通过 totalSeconds % 60 得到当前秒数(例如:秒 % 60 = 8,这个值就是当前秒数)。
4)通过将 totalSeconds 除以 60 得到总的分钟数 totalMinutes (例如:秒 / 60 = 分钟)。
5)通过 totalMinutes % 60 得到当前分钟数(例如: 分钟 % 60 = 31,这个值就是当前分钟数)。
6)通过 totalMinutes 除以 60 获得总的小时数 totalHouse(例如:分钟 / 60 = 小时)。
7)通过 totalHouse % 24 得到当前的小时数(例如: 小时 % 24 = 17,该值就是当前小时数)。
程序清单2-7:
package Chapter_03; import java.util.Scanner; public class Code_01 { public static void main(String[] args) { 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; System.out.println("Current time is " + currentHour + ":" + currentMinute + ":"+currentSecond + " GMT"); } }
讯享网
输出
讯享网Current time is 14:32:31 GMT
2.8程序代码:
package Chapter_03; import java.util.Scanner; public class Test2_8 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the time zone offset to GMT:"); int offset = input.nextInt(); // 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; totalSeconds += offset * 60 * 60; // 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; // Display results System.out.println("Current time is " + currentHour + ":" + currentMinute + ":" + currentSecond + " GMT"); } }
输出:
讯享网Enter the time zone offset to GMT:-5 Current time is 23:25:32 GMT

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/98078.html