Write a program to count the number of days between two dates.

The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.

Example 1:
Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1

Example 2:
Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15

Constraints:

  • The given dates are valid dates between the years 1971 and 2100.

Solution in python:

class Solution:
    def daysBetweenDates(self, date1: str, date2: str) -> int:
        def isYear(num):
            if ((num % 4 == 0) and (num % 100) != 0) or (num % 400 == 0):
                return True
            return False
        def numofday(date):
            days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
            time = date.split('-')
            flag = isYear(int(time[0]))
            count = 0
            for i in range(int(time[1])-1):
                count += days[i]
            if not flag and int(time[1]) > 2:
                count -= 1
            count += int(time[2])
            return count
        if date2 < date1:
            date2, date1 = date1, date2
        day1 = numofday(date1)
        day2 = numofday(date2)
        year1 = int(date1.split('-')[0])
        year2 = int(date2.split('-')[0])
        days = 0
        for year in range(year1, year2):
            if isYear(year):
                days += 366
            else:
                days += 365
        return days - day1 + day2
最后修改日期: 2021年3月10日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。