Java练习题–日期差值
题目描述
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。
输入格式
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD
输出格式
每组数据输出一行,即日期差值
样例输入
20130101
20130105
样例输出
5
Java代码
自己计算
import java.util.Scanner;
public class DateDifference {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String date1 = scanner.nextLine();
String date2 = scanner.nextLine();
String date3;
if(Integer.parseInt(date1)>Integer.parseInt(date2)){
date3 = date1;
date1 = date2;
date2 = date3;
}
int diff = difference(date1, date2);
System.out.println(diff);
}
}
/*计算差值*/
public static int difference(String date1, String date2){
//划分获取年、月、日
int year1 = Integer.parseInt(date1.substring(0,4));
int month1 = Integer.parseInt(date1.substring(4,6));
int day1 = Integer.parseInt(date1.substring(6,8));
int year2 = Integer.parseInt(date2.substring(0,4));
int month2 = Integer.parseInt(date2.substring(4,6));
int day2 = Integer.parseInt(date2.substring(6,8));
int diff = 1;
int[] m1 = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int[] m2 = {0,31,28,31,30,31,30,31,31,30,31,30,31};
// 闰年
if(IsLeapYear(year1)){
m1[2] = 29;
}
if(IsLeapYear(year2)){
m2[2] = 29;
}
// 年份相同
if(year2 == year1){
// 月份相同
if(month2 == month1){
// 计算日差值(day2-day1+1)
if(day2 >= day1){
diff = day2 - day1 + diff;
}
}
// 月份不同(day2+m[month2-1]+……+m[month1+1]+(m[month1]-day1)+1)
else if(month2 > month1){
int diffMonth = month2 - month1;
diff = m1[month1] - day1 + day2 + diff;
if(diffMonth > 1){
for(int i=1; i<diffMonth; i++){
diff = diff + m1[month1+i];
}
}
}
}
// 年份不同[(m[month1]-day1+m[month1+1]+……+m[12])+(year1+1)+……+(year2-1)+(m[1]+……+m[month2-1]+day2)+1]
else if(year2 > year1){
int diffYear = year2 - year1;
diff = day2 + diff;
if(month2 > 1){
for(int i=1;i<month2;i++){
diff = diff + m2[i];
}
}
diff = diff + m1[month1] - day1;
if(month1 < 12){
for(int i=month1+1;i<13;i++){
diff = diff + m1[i];
}
}
if(diffYear>1){
for(int i=1;i<diffYear;i++){
if(IsLeapYear(year1+i)){
diff = diff + 366;
}
else{
diff = diff + 365;
}
}
}
}
return diff;
}
/*判断是否闰年*/
public static boolean IsLeapYear(int year){
if((year%4==0 && year%100!=0) || year%400==0){
return true;
}
else{
return false;
}
}
}
调用Java类
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;
public class DateDifference1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
//设定输入的字符串时间格式,并把字符串转换为时间
LocalDate ld1=LocalDate.parse(sc.next(), DateTimeFormatter.ofPattern("yyyyMMdd"));
LocalDate ld2=LocalDate.parse(sc.next(),DateTimeFormatter.ofPattern("yyyyMMdd"));
if(ld1.until(ld2, ChronoUnit.DAYS)>0){
System.out.println(ld1.until(ld2, ChronoUnit.DAYS)+1);//计算二者相差时间
}else{
System.out.println(ld1.until(ld2, ChronoUnit.DAYS)*(-1)+1);
}
}
}
}