Create Effective Date of Birth Form

Key challenges

Collecting dates of birth from international users can present several challenges, including differences in date format, language barriers, and cultural differences in how dates are expressed.

Despite these challenges, it is necessary to normalize dates into a standard format for use in a global system, which accepts only dates of birth that are in ISO 8601 format (YYYY-MM-DD) for consistency and accuracy.

Best practices

Consider these best practices for capturing and translating user dates of birth into ISO 8601 format:

The following script can be used to assist in this process:

Python

import re
from datetime import datetime

def convert_date(date_string):
    # Map each strptime format to a regular expression that recognizes it.
    date_formats = {
        "%Y-%m-%d": r"^\d{4}-\d{2}-\d{2}$",            # ISO 8601: China, Japan, Korea, Sweden, etc.
        "%m/%d/%Y": r"^\d{2}/\d{2}/\d{4}$",            # United States and English Canada
        "%d-%m-%Y": r"^\d{2}-\d{2}-\d{4}$",            # United Kingdom, Ireland, Australia, India, etc.
        "%Y/%m/%d": r"^\d{4}/\d{2}/\d{2}$",            # Iran, Iraq
        "%Y.%m.%d": r"^\d{4}\.\d{2}\.\d{2}$",          # Indonesia, Mongolia, South Korea, etc.
        "%d.%m.%Y": r"^\d{2}\.\d{2}\.\d{4}$",          # Croatia, Lithuania, Serbia, Slovakia, etc.
        "%b %d, %Y": r"^[A-Za-z]{3} \d{1,2}, \d{4}$",  # E.g. Jan 30, 2020 - US and English Canada
        "%d %b %Y": r"^\d{1,2} [A-Za-z]{3} \d{4}$",    # E.g. 30 Jan 2020 - India, Malaysia, Singapore
        "%Y년 %m월 %d일": r"^\d{4}년 \d{1,2}월 \d{1,2}일$",  # North and South Korea
        "%Y年%m月%d日": r"^\d{4}年\d{1,2}月\d{1,2}日$",       # China, Japan
    }

# Iterate over the formats and return the first one that matches.
    for date_format, date_regex in date_formats.items():
        if re.match(date_regex, date_string):
            # Parse the string into a datetime using the matching format.
            return datetime.strptime(date_string, date_format)

# If the date string doesn't match any known format, raise a ValueError.
    raise ValueError(f"Unrecognized date format: {date_string}")

print(convert_date("01/02/2020").date())  # 2020-01-02
print(convert_date("02-01-2020").date())  # 2020-01-02
print(convert_date("2020年1月2日").date())  # 2020-01-02

You can use the following regex to determine when an exception needs to be displayed:

^([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])([Zz]|[+-][0-9]{2}:[0-9]{2})?$

Updated 2 days ago