importjavax.swing.JOptionPane;publicclassDisplaydate{publicstaticvoidmain(String[]args){longtotalMilliseconds=System.currentTimeMillis();longtotalSeconds=(totalMillisecon...
import javax.swing.JOptionPane;
public class Displaydate{
public static void main(String[] args){
long totalMilliseconds = System.currentTimeMillis();
long totalSeconds = (totalMilliseconds / 1000);
int currentSecond = (int)(totalSeconds % 60);
long totalMinutes = totalSeconds / 60;
int currentMinute = (int)(totalMinutes % 60);
long totalHours = totalMinutes / 60;
int currentHour = (int)(totalHours % 24);
int totalDays = (int)(totalHours / 24);
if (currentSecond > 0)
totalDays++;
//已经过去的整年
int currentYear = 1970;
do {
currentYear++;
} while (SumDayYear(currentYear) < totalDays);
//已经过去的整月
int totalNumOfDaysInTheYear = totalDays -SumDayYear(currentYear - 1);
int currentMonth = 0;
do {
currentMonth++;
} while (SumDaysMonths(currentYear, currentMonth)< totalNumOfDaysInTheYear);
//当前的天
int currentDay = totalNumOfDaysInTheYear -SumDaysMonths(currentYear, currentMonth - 1);
String output = "Current date and time is " + currentYear + " "
+currentMonth + "/" + currentDay + "/" +
currentHour + ":" +currentMinute + ":" + currentSecond;
JOptionPane.showMessageDialog(null, output);
}
static int SumDayYear(int year) {
int result1 = 0;
for (int i = 1970; i <= year; i++)
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
result1+= 366;
else
result1+= 365;
return result1;
}
static int SumDaysMonths(int year, int month) {
int result2 = 0;
for (int i = 1; i <= month; i++)
result2+=HowmanyDaysInMonth(year, i);
return result2;
}
static int HowmanyDaysInMonth(int year, int month){
if (month == 1 || month==3 || month == 5 || month == 7 ||month == 8 || month == 10 || month == 12)
return 31;
if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;
if (month == 2)
if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
return 29;
else
return 28;
return -1;
}
}
输出的月份日期不对,因为学到这一章只能用这种方法做,求指点
已经解决了谢谢各位
展开