显示当前的时间

问题:开发一个显示当前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型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值