注意事项:
1:long totalsec=(long)(System.currentTimeMillis()/1000);//获取从1970年1月1日至今的总毫秒数
,并且将总毫秒数转化为秒数
2:计算出总秒数totalsec,依次转换为年月日时分秒,转换为年月后,用totalsec取整取余的方法来计算时分秒比较简单
3:将月份用字符串表示String Months;//将确定月份转换成英文格式
switch (month)
4:输出days应该+1,因为是从1970年1号开始计算日期的
5: 用数组存储一个月的天数:int day[]={ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
代码:
<pre class="cpp" name="code">import java.util.*;
public class Currenttime {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
long totalsec = (long) (System.currentTimeMillis() / 1000);// 获取从1970年1月1日至今的总毫秒数
// 并且将总毫秒数转化为秒数;
int day[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int year = 1970, month = 1, days, hours, minutes, seconds;
long yearsec = 365 * 24 * 3600;
long daysec = 24 * 3600;
long hoursec = 3600;
long minutesec = 60;
while (totalsec > yearsec)// 确定年数
{
totalsec -= yearsec;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
totalsec -= daysec;
year++;
}
int i = 1;// 确定月份
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
// 确定年份后如果今年是闰年则2月为29天,否则不变
day[2] = 29;
while (totalsec >= daysec * day[i]) {
month++;
totalsec -= daysec * day[i];
i++;
}
String Months;// 将确定月份转换成英文格式
switch (month) {
case 1:
Months = "January";
break;
case 2:
Months = "February";
break;
case 3:
Months = "March";
break;
case 4:
Months = "April";
break;
case 5:
Months = "May";
break;
case 6:
Months = "June";
break;
case 7:
Months = "Jule";
break;
case 8:
Months = "August";
break;
case 9:
Months = "September";
break;
case 10:
Months = "October";
break;
case 11:
Months = "November";
break;
case 12:
Months = "December";
break;
default:
Months = "Error!";
break;
}
days = (int) (totalsec / daysec);// 确定日期
totalsec %= daysec;
hours = (int) (totalsec / hoursec);// 确定小时
totalsec %= hoursec;
minutes = (int) (totalsec / minutesec);// 确定分钟
totalsec %= minutesec;// 确定秒数
System.out.println("Current date and time is " + Months + " "
+ (days + 1) + " " + year + " " + hours + ": " + minutes + ": "
+ totalsec);
}
}
问题:但是输出时间为什么老是只有小时是错误的,而年月日分钟秒钟却是对的