问题:开发一个显示当前GMT(格林威治标准时间)的程序,格林威治时间的格式为小时:分钟:秒(hour:minute:second),例如:13:19:8.
System类中的方法currentTimeMillis返回从GMT1970年1月1日00:00:00开始到现在当前时刻的毫秒数。
程序的思路:
1)调用System.currentTimeMillis()方法获取存放在变量totalMilliseconds中从1970年1月1日午夜到现在的毫秒数。
2)通过将总毫秒数totalMilliseconds除以1000得到总秒数totalSeconds。
3)通过totalSeconds%60得到当前的秒数。
4)通过将totalSeconds除以60得到总的分钟数totalMinutes。
5)通过totalminutes%60得到当前分钟数。
6)通过将总分钟数totalMinutes除以60获得总的小时数totalHours。
7)通过totalHours%24得到当前的小时数。
程序清单ShowCurrentTime.java给出完整的程序。
public class ShowCurrentTime {
public static void main(String args[]){
//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;
//Display results
System.out.println("Current time is "+currentHour+":" +currentMinute+":"+currentSecond+" GMT");
}
}
注意:当调用System.currentTimeMillis()时,它返回GMT当前时间与1970年1月1日0点之间单位为毫秒的差值。这个方法返回一个long型的毫秒值。因此,在该程序中的所有变量都被声明为long型。