java计算两日期间隔天数
答案:1 悬赏:10 手机版
解决时间 2021-02-18 11:34
- 提问者网友:我是我
- 2021-02-18 06:20
java如何正确地计算出两个日期之间的天数是多少?哪位帮帮忙……
最佳答案
- 五星知识达人网友:西岸风
- 2021-02-18 07:33
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;public class CompareTime { public static void main(String[] args) {
String t1 = "1990-1-1";
String t2 = "2000-1-1"; try {
System.out.println(CompareTime.getBetweenDays(t1, t2));
} catch (ParseException e) {
e.printStackTrace();
}
} 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);
// 保证第二个时62616964757a686964616fe78988e69d8331333332623330间一定大于第一个时间
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;
}} 这个应该可以的,以前用过,试试看
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;public class CompareTime { public static void main(String[] args) {
String t1 = "1990-1-1";
String t2 = "2000-1-1"; try {
System.out.println(CompareTime.getBetweenDays(t1, t2));
} catch (ParseException e) {
e.printStackTrace();
}
} 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);
// 保证第二个时62616964757a686964616fe78988e69d8331333332623330间一定大于第一个时间
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;
}} 这个应该可以的,以前用过,试试看
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯