您的位置:首页 > 编程语言 > Java开发

JAVA Current date and time

2015-09-22 20:02 537 查看

项目要求

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***
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: