请各位大哥大姐帮小弟计算一下天数!
小弟在此请教各位了![color=#FF0000][/color]
顺便给小弟更正一下呗![b][/b]
import java.util.*;
public class CountDay {
public int tianshu(int year,int month,int day){
int ds1=day;//存放累加当年距离1月1日的天数
switch(month-1){
case 11:ds1+=30;
case 10:ds1+=31;
case 9:ds1+=30;
case 8:ds1+=31;
case 7:ds1+=31;
case 6:ds1+=30;
case 5:ds1+=31;
case 4:ds1+=30;
case 3:ds1+=31;
case 2:
if(year%4==0&&year%100!=0 ||year%400==0)
ds1+=29;//闰年2月29天
else
ds1+=30;//平年2月28天
case 1:ds1+=31;
}
/**
* 计算当年距离1991/1/1日的天数
*/
int years;//存放距离1900年之间的年份
int ds2=0;//存放距离1900年之间整年的天数和
for( years=year-1;years>=1900;years++){
if(years%4==0&&years%100!=0 ||years%400==0)
ds2+=366;//闰年366天
else
ds2+=355;//平年355天
}
int ds = ds1+ds2;//存放输入的日期距离1900/1/1的总天数
return ds;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("请输入年份");
year = input.nextInt();
System.out.print("请输入月份");
month = input.nextInt();
System.out.print("请输入日子");
day = input.nextInt();
int sum = a.tianshu(b.year,b.month,b.day);
System.out.println("距离1990/1/1的天数:"+sum);
}
}
运行结果:
请输入年份1903
请输入月份3
请输入日子3
距离1990/1/1的天数:-714718526结果为啥是这个啊!天数应该是:1158[b][/b]
------解决方案--------------------用calendar多好~~~~
------解决方案-------------------- public static int getBetweenDays(String t1, String t2)
throws
ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
int betweenDays = 0;
Date d1 = format.parse(t1);
Date d2 = format.parse(t2);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
// 保证第二个时间一定大于第一个时间
if (c1.after(c2)) {
c1 = c2;
c2.setTime(d1);
}
int betweenYears = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
betweenDays = c2.get(Calendar.DAY_OF_YEAR)
- c1.get(Calendar.DAY_OF_YEAR);
for (int i = 0; i < betweenYears; i++) {
c1.set(Calendar.YEAR, (c1.get(Calendar.YEAR) + 1));
betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR);
}
return betweenDays;
}
}
------解决方案--------------------楼上的方法可以,不过,betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR);
要改成
betweenDays += c1.getActualMaximum(Calendar.DAY_OF_YEAR);
简单的方法
public static float getDaysBetweenDates(Date d1, Date d2)
{
float days = (float) (d1.getTime() - d2.getTime())
/ (1000 * 60 * 60 * 24);
return Math.abs(days);
}
还有 1903 到 1990 怎么会 是 1158 ??
87年才1158天? 不对吧,
请输入年份1903
请输入月份3
请输入日子3
距离1990/1/1的天数:-714718526
结果为啥是这个啊!天数应该是:1158[b][/b]