在试图用代码实现时间戳转换为标准时间(作业)。在实现getMonth方法的时候,希望把剩余天数用数组月份遍历的时候依次减出来,代码如下:
public class TimeStamp {
public long getYear()
{
return (int)(System.currentTimeMillis()/(1461*24*3600d*1000)*4+1970);
}
public double getMonth() {
//用总天数day-已经过去年份的天数,然后减去每个月的天数,挨个月份遍历
//先求天数:
double day =(long) (System.currentTimeMillis() / (24 * 3600d*1000));
int passDays = 0;
int[] rMonth = new int[]{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//闰年月天数
int[] pMonth = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//平年月天数
for (int c = 1970; c < getYear(); c++)//计算天数循环,到2015年整个结束共计的天数
{
int a = 365;
if (c % 4 == 0)
a = 366;
passDays = passDays + a;//总计从时间戳开始过去的天数
}
double leftDays=0;//完整年减去后剩下的天数
leftDays=System.currentTimeMillis()/(24*3600d*1000)-passDays;
leftDays=(int)leftDays;//剩下的天数返回的是对的===========================================================
//=======================================================
//创造一个for循环一个月一个月的遍历减去天数
for(int i=0;i<=11;i++)
{
if (getYear()%4==0)
day=leftDays-rMonth[i];
if (getYear()%4!=0)
day = leftDays - pMonth[i];
if (day<=0)
break;
}
return day/*由于此处未正确实现,仅先作为一个返回值测试点用*/;
}
public static void main(String args[])
{
TimeStamp time=new TimeStamp();
System.out.println(time.getMonth());
}
}
一部分代码如上,运行后直到返回的leftDays的值都是对的,到了getMonth方法的循环之后,dayDate返回的数值可以看出只执行了一次循环,这是什么问题?
The reason is that I only operate one variable day in each loop and forget to operate the leftDays variable, which makes each loop equivalent to recalculating day, which is of no use. . . Problem solved