JAVA Current date and time

项目要求

Invoking System.currentTimeMillis() returns the elapse time in milliseconds since midnight of January 1,1970.Write a program that displays the date and time.Here is a sample run:

Current date and time is May 16, 2009 10:34:23

代码如下

public class CurrentTime {
	public static void main(String[] args) {
		long currentSec = (long) (System.currentTimeMillis() / 1000);// 将毫秒/1000转换为秒
		long lastSec = 0;// 剩余秒数
		long yearSec = 31536000;// 365*24*60*60,即一年的秒数
		long oneDaySec = 86400;// 24*60*60,即一天的秒数
		long hourSec = 3600;// 60*60,即一小时的秒数

		int[] day = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		int year, month;

		for (year = 1970; currentSec - lastSec >= yearSec; year++) {
			lastSec += yearSec;

			if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
				lastSec += oneDaySec;// 闰年多一天
			}
		}
		if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
			day[2] = 29;
		} else
			day[2] = 28;

		for (month = 0; currentSec - lastSec >= oneDaySec * 28; month++) {
			lastSec += day[month] * oneDaySec;// 计算出月份
		}

		String monthS;// 将月份转为英文
		switch (month) {
		case 1:
			monthS = "Jan";
			break;
		case 2:
			monthS = "Feb";
			break;
		case 3:
			monthS = "Mar";
			break;
		case 4:
			monthS = "Apr";
			break;
		case 5:
			monthS = "May";
			break;
		case 6:
			monthS = "Jun";
			break;
		case 7:
			monthS = "Jul";
			break;
		case 8:
			monthS = "Aug";
			break;
		case 9:
			monthS = "Sep";
			break;
		case 10:
			monthS = "Oct";
			break;
		case 11:
			monthS = "Nov";
			break;
		case 12:
			monthS = "Dec";
			break;
		default:
			monthS = "error!";
			break;
		}

		long last = currentSec - lastSec;// 用last记录每次计算时分秒后的剩余秒数

		long date = last / oneDaySec;
		last -= date * oneDaySec;

		long hour = last / hourSec;
		last -= hour * hourSec;

		long minute = last / 60;
		last -= minute * 60;

		long second = last;

		System.out.print("Current date and time is " + monthS + " " + date
				+ ", " + year + " " + hour + ":" + minute + ":" + second);
		System.out.printf(
				"\nCurrent date and time is %s %d, %2d %02d:%02d:%02d", monthS,
				date, year, hour, minute, second);
		// 用printf标准化格式
	}

}

运行结果

Current date and time is Sep 21, 2015 11:57:0
Current date and time is Sep 21, 2015 11:57:00

学习心得

还是蛮有成就感的…研究printf的格式也是研究了半天,以前学C++没有用过,感觉还是很好用的

%02d即保证两位数,位数不足用0占位,从运行结果可以看出标准化格式前后区别


题目来自《JAVA语言程序设计》P196 5.33***

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值