Using datetime library in your choice of language makes it easy to write a program to find the number of days between two dates. We write code with and without using the library.

Let’s first find the number of days between two dates with using a library:

1. Prompt the user to enter the first date in a specific format (e.g., “dd/mm/yyyy”).

2. Validate the user input to ensure that it is a valid date format.

3. Convert the inputted date string to a date object. Leetcode 463 Island Perimeter

4. Prompt the user to enter the second date in the same format.

5. Validate the user input to ensure that it is a valid date format.

6. Convert the inputted date string to a date object.

7. Calculate the difference between the two dates in days by subtracting the earlier date from the later date.

8. Print the number of days between the two dates to the console.

import datetime

# Prompt user to enter the first date
date1_str = input("Enter the first date (dd/mm/yyyy): ")

# Validate the user input
try:
    date1 = datetime.datetime.strptime(date1_str, '%d/%m/%Y').date()
except ValueError:
    print("Invalid date format entered.")
    exit()

# Prompt user to enter the second date
date2_str = input("Enter the second date (dd/mm/yyyy): ")

# Validate the user input
try:
    date2 = datetime.datetime.strptime(date2_str, '%d/%m/%Y').date()
except ValueError:
    print("Invalid date format entered.")
    exit()

# Calculate the difference in days
delta = date2 - date1
days_diff = delta.days

# Print the number of days between the two dates
print(f"There are {days_diff} days between {date1} and {date2}.")

This program first prompts the user to enter two dates in the specified format. It then validates the user input using the strptime() method from the datetime module to ensure that the inputted strings are in the correct format. If the inputted strings are not valid dates, the program prints an error message and exits.

See also  Detect loop in linked list using Floyd's algorithm

If the inputted strings are valid dates, the program converts them to date objects using the date() method. It then calculates the difference between the two dates in days using the days attribute of a timedelta object created by subtracting the earlier date from the later date.

Finally, the program prints the number of days between the two dates to the console.

Find the number of days between two dates with using a library

# Prompt user to enter the first date
date1_str = input("Enter the first date (dd/mm/yyyy): ")

# Validate the user input
try:
    day1, month1, year1 = map(int, date1_str.split('/'))
    if not (1 <= day1 <= 31 and 1 <= month1 <= 12 and 1 <= year1 <= 9999):
        raise ValueError
except ValueError:
    print("Invalid date format entered.")
    exit()

# Prompt user to enter the second date
date2_str = input("Enter the second date (dd/mm/yyyy): ")

# Validate the user input
try:
    day2, month2, year2 = map(int, date2_str.split('/'))
    if not (1 <= day2 <= 31 and 1 <= month2 <= 12 and 1 <= year2 <= 9999):
        raise ValueError
except ValueError:
    print("Invalid date format entered.")
    exit()

# Calculate the number of days that have passed since the beginning of the year for the first date
days_in_month1 = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year1 % 4 == 0 and (year1 % 100 != 0 or year1 % 400 == 0):
    days_in_month1[2] = 29
days_passed1 = sum(days_in_month1[:month1]) + day1 - 1

# Calculate the number of days that have passed since the beginning of the year for the second date
days_in_month2 = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year2 % 4 == 0 and (year2 % 100 != 0 or year2 % 400 == 0):
    days_in_month2[2] = 29
days_passed2 = sum(days_in_month2[:month2]) + day2 - 1

# Calculate the number of days between the two years, accounting for leap years
days_between_years = sum(366 if (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)) else 365 for year in range(year1, year2))

# Calculate the total number of days between the two dates
if year1 == year2:
    days_diff = days_passed2 - days_passed1
else:
    days_diff = days_between_years - days_passed1 + days_passed2

# Print the number of days between the two dates to the console
  1. The code first prompts the user to enter two dates in the specified format (e.g., “dd/mm/yyyy”).
  2. It then validates the user input to ensure that the inputted strings are in the correct format and have valid values for the day, month, and year components of a date. If the inputted strings are not valid dates, the program prints an error message and exits.
  3. After the input validation, the code parses each inputted date string into day, month, and year integers using the split() method to separate the values.
  4. The code then calculates the number of days that have passed since the beginning of the year for the first date. It starts by creating a list of the number of days in each month of the year and checks for a leap year by checking whether the year is divisible by 4 and not divisible by 100, or divisible by 400. Then, it sums the number of days in the months up to the given month and adds the number of days in the given month, minus one (since we don’t want to include the current day), to get the total number of days passed so far in the given year.
  5. Similarly, the code calculates the number of days that have passed since the beginning of the year for the second date using the same method as for the first date.
  6. The code then calculates the number of days between the two years by iterating over each year between the two dates and adding the number of days in each year, accounting for leap years.
  7. The code then calculates the total number of days between the two dates by either subtracting the days passed so far in the first year from the total number of days in the years between the two dates, or simply subtracting the days passed so far in the first date from the days passed so far in the second date if both dates are in the same year.
  8. Finally, the program prints the number of days between the two dates to the console.
See also  String to Integer (atoi)

Written by

With 10+ years in software engineering, I specialize in blogging and web development. My skills span front-end, back-end, database design, web security, and SEO. Passionate about crafting helpful digital experiences.