JAVA Current date and time

来源:互联网 发布:淘宝网店转让有风险吗 编辑:程序博客网 时间:2024/05/18 03:56

项目要求

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;} elseday[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:0Current date and time is Sep 21, 2015 11:57:00

学习心得

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

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


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

0 0
原创粉丝点击