Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How to check if a variable (date) is in the correct format.

+29 votes
asked Nov 15, 2024 by Taylor Corbin (330 points)

How do you check if a date that has been inputed as a variable and it is in the format DD/MM/YYYY

2 Answers

0 votes
answered Nov 16, 2024 by konda lingala24 (440 points)
selected Dec 16, 2024 by Taylor Corbin
 
Best answer
from datetime import datetime

# Input: Date string
date_input = input("Enter a date in DD/MM/YYYY format: ")

# Function to validate the date format
def validate_date_format(date_string):
    try:
        # Attempt to parse the date string
        parsed_date = datetime.strptime(date_string, "%d/%m/%Y")
        print(f"Valid date: {parsed_date.strftime('%d/%m/%Y')}")
        return True
    except ValueError:
        # If parsing fails, it's not a valid format
        print("Invalid date format. Please use DD/MM/YYYY.")
        return False

# Validate the input date
validate_date_format(date_input)
commented Jan 16, 2025 by ??? (160 points)
I need this answer too.Thanks.
commented Jan 16, 2025 by ??? (160 points)
I'm from china.
+2 votes
answered Nov 18, 2024 by Peter Minarik (101,420 points)

What language are we talking about?

  1. You can write your own format checker function where you could for instance split the input string alongside the / characters and check all 3 parts if they are as expected
  2. Most programming languages have a way to parse date from string and if it fails, it would throw an error. You just need to catch that error to know if the date was not in an acceptable format.
commented Nov 29, 2024 by Taylor Corbin (330 points)
It is in Python
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...