下面是一个运行示例:
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日午夜到现在的毫秒数(例如:1203183086328毫秒),并且存放在变量 totalMilliseconds 中。
2)通过将毫秒数 totalMilliseconds 除以 1000 得到总毫秒数 totalseconds (例如:1203183086328毫秒 / 1000 = 1203183068)。
3)通过 totalSeconds % 60 得到当前秒数(例如:1203183068秒 % 60 = 8,这个值就是当前秒数)。
4)通过将 totalSeconds 除以 60 得到总的分钟数 totalMinutes (例如:1203182068秒 / 60 = 20023051分钟)。
5)通过 totalMinutes % 60 得到当前分钟数(例如:20053051 分钟 % 60 = 31,这个值就是当前分钟数)。
6)通过 totalMinutes 除以 60 获得总的小时数 totalHouse(例如:20053051分钟 / 60 = 334217小时)。
7)通过 totalHouse % 24 得到当前的小时数(例如: 334217 小时 % 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