Validate Date in Different formats using C#.net


There are situation where we need to validate dates received in different formats and we want to make sure that the given date is valid as per the format required.


                
//Example 1 - Validate Date for the format DD/MM/YYYY 
private bool ValidateDate(string stringDateValue)
{
    try
    {
        CultureInfo CultureInfoDateCulture = new CultureInfo("fr-FR");
        DateTime d = DateTime.ParseExact(stringDateValue, "dd/MM/yyyy", CultureInfoDateCulture);
        return true;
    }
    catch
    {
        return false;
    }
}

//Example 2 - Validate Date for the format MM/DD/YYYY 
private bool ValidateDate(string stringDateValue)
{
    try
    {
        CultureInfo CultureInfoDateCulture = new CultureInfo("en-US");
        DateTime d = DateTime.ParseExact(stringDateValue, "MM/dd/yyyy", CultureInfoDateCulture);
        return true;
    }
    catch
    {
        return false;
    }
}

//Example 3 - Validate Date for the format YYYY/MM/DD 
private bool ValidateDate(string stringDateValue)
{
    try
    {
        CultureInfo CultureInfoDateCulture = new CultureInfo("ja-JP");
        DateTime d = DateTime.ParseExact(stringDateValue, "yyyy/MM/dd", CultureInfoDateCulture);
        return true;
    }
    catch
    {
        return false;
    }
}

Example 3 - Validate Date for the format DDMMYYYY 
private bool ValidateDate(string stringDateValue)
{
    try
    {
        CultureInfo CultureInfoDateCulture = new CultureInfo("fr-FR");
        DateTime d = DateTime.ParseExact(stringDateValue, "ddMMyyyy", CultureInfoDateCulture);
        return true;
    }
    catch
    {
        return false;
    }
}

//Example 4 - Validate Date for the format MMDDYYYY 
private bool ValidateDate(string stringDateValue)
{
    try
    {
        CultureInfo CultureInfoDateCulture = new CultureInfo("en-US");
        DateTime d = DateTime.ParseExact(stringDateValue, "MMddyyyy", CultureInfoDateCulture);
        return true;
    }
    catch
    {
        return false;
    }
}

//Example 5 - Validate Date for the format MMDDYYYYHHMMSS 
private bool ValidateDate(string stringDateValue)
{
    try
    {
        CultureInfo CultureInfoDateCulture = new CultureInfo("en-US");
        DateTime d = DateTime.ParseExact(stringDateValue, "MMddyyyyHHmmss", CultureInfoDateCulture);
        return true;
    }
    catch
    {
        return false;
    }
}

Welcome Guest
Sign In | Register