题目:
给定两个日期,请你计算这两个日期之间有少天(定义连续的日期之差为2天)
输入格式:
共两行,每一行输入一个日期,日期格式为yyyy-MM-dd
输出格式:
一个正整数,为两个日期之间的差
输入样例:
2021-07-02
2021-07-15
输出样例:
14
解法一:(c++)
#include<iostream>
using namespace std;
int mon[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
bool judgeYear(int year)
{
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return true;
else
return false;
}
int getDays(int year, int month, int day)
{
if (judgeYear(year)) mon[2] = 29;
int sumday=0;
for (int i = 0; i < month; i++)
sumday += mon[i];
sumday += day;
return sumday;
}
int main()
{
//2021-07-02
//2021-07-15
int year1, year2, month1, month2, day1, day2;
char a;
cin >> year1 >> a >> month1 >> a >> day1;
cin >> year2 >> a >> month2 >> a >> day2;
//int year1 = 2021, month1 = 7, day1 = 2;
//int year2 = 2022, month2 = 7, day2 = 15;
int sum = 0;
for (int i = year1; i < year2; i++)
{
if (judgeYear(i)) sum += 366;
else sum += 365;
}
int a1 = getDays(year1, month1, day1);
int a2 = getDays(year2, month2, day2);
if (a1 > a2)
sum -= (a1 - a2);
else
sum += (a2 - a1);
cout << sum+1;
return 0;
}
解法二:(java)
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
//2021-08-06
//2020-06-09
Scanner scanner = new Scanner(System.in);
String temp1 = scanner.nextLine();
String temp2 = scanner.nextLine();
String[] a1 = new String[4];
String[] a2 = new String[4];
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
Date date = dateFormat.parse(temp1);
a1 = temp1.split("-");
a2 = temp2.split("-");
LocalDate dateBefore = LocalDate.of(Integer.parseInt(a1[0]), Integer.parseInt(a1[1]), Integer.parseInt(a1[2]));
LocalDate dateAfter = LocalDate.of(Integer.parseInt(a2[0]), Integer.parseInt(a2[1]), Integer.parseInt(a2[2]));
//ChronoUnit.DAYS.between源码 默认为long型
long daysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);
System.out.println(daysBetween);
}
}