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

Introduction to Java Programming编程题5.33<显示当前日期和时间>

2015-08-19 18:18 856 查看
/*
Current data and time is August 18, 2015 6:8:23.
*/
public class CurrentTime {
public static void main(String[] args) {
showTime();
}

public static void showTime() {
final long PER_SECONDS_DAY =  60 * 60 * 24;
long totalSeconds = (System.currentTimeMillis() + 8 * 60 * 60 * 1000) / 1000;
long totaldays = totalSeconds / PER_SECONDS_DAY;

System.out.print("Current data and time is ");
showCurrentData(totaldays);
showCurrentTime(totalSeconds);
}

public static void showCurrentTime(long totalSeconds) {
long seconds = totalSeconds % 60;
long minutes = totalSeconds / 60 % 60;
long hours = totalSeconds / 60 / 60 % 24;
System.out.println(" " + hours + ":" + minutes + ":" + seconds + ".");
}

public static boolean isLeapYear(long year) {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
return true;
else
return false;
}

public static void showCurrentData(long totaldays) {
final int START_YEAR = 1970;
int days, currentYear;

for (currentYear = START_YEAR; totaldays >= 365; currentYear++) {
if (isLeapYear(currentYear))
days = 366;
else
days = 365;
totaldays -= days;
}

int month = 1;
int n = perMonthDay(currentYear, month);
while (totaldays > n) {
totaldays -= n;
month++;
n = perMonthDay(currentYear, month);
}
totaldays++;
System.out.print(toMonthLetter(month) + " " + totaldays + ", " + currentYear);
}

public static String toMonthLetter(int month) {
String monthLetter = "";
switch (month) {
case 1: monthLetter = "January"; break;
case 2: monthLetter = "February"; break;
case 3: monthLetter = "March";  break;
case 4: monthLetter = "April";  break;
case 5: monthLetter = "May";    break;
case 6: monthLetter = "June";   break;
case 7: monthLetter = "July";   break;
case 8: monthLetter = "August"; break;
case 9: monthLetter = "September";  break;
case 10: monthLetter = "October";   break;
case 11: monthLetter = "November";  break;
case 12: monthLetter = "December";  break;
}

return monthLetter;
}
public static int perMonthDay(int currentYear, int month) {
int n;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
n = 31;
break;
case 2:
if (month == 2) {
if (isLeapYear(currentYear))
n = 29;
else
n = 28;
break;
}
default: n = 30;
}

return n;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: