locked
C# valid datetime value RRS feed

  • Question

  • In a C# 2008 application, I am obtaining a data from a web service via an xml file. In some instance a field is not a must not be a valid datetime value for a sql server 2008 r2 database.
    Thus can you tell me:
    1. what check I can do to make certain the value is in a valid date time format?
    2. Also can you tell me how to convert the value to a valid datetime format?
    Thursday, October 18, 2012 4:19 PM

Answers

  • You can use DateTime.TryParse or TryParseExact (if you know the format of the incoming DateTime Value).

    object dateTimeValue = GetDateTimeValueFromDB();
    DateTime dt;
    
    if(!DateTime.TryParse(Convert.ToString(dateTimeValue), out dt))
    {
        //Value is not in valid DateTime format
    }
    else
    {
        //dt containes DateTime value
    }
     

    I hope this helps.

    Please mark this post as answer if it solved your problem. Happy Programming!

    • Proposed as answer by Norkk Thursday, October 18, 2012 4:31 PM
    • Marked as answer by Bob Shen Tuesday, October 23, 2012 7:01 AM
    Thursday, October 18, 2012 4:31 PM
  • Wendy : Hope the below helps

    DateTime objDate;
    if(DateTime.TryParse(yourdatevalue,out objDate))
    {
       //1. is valid date
    }
    else
    {
       //Not valid
       //2. To code based on you input value
    }

    • Marked as answer by Bob Shen Tuesday, October 23, 2012 7:01 AM
    Thursday, October 18, 2012 4:29 PM

All replies

  • Wendy : Hope the below helps

    DateTime objDate;
    if(DateTime.TryParse(yourdatevalue,out objDate))
    {
       //1. is valid date
    }
    else
    {
       //Not valid
       //2. To code based on you input value
    }

    • Marked as answer by Bob Shen Tuesday, October 23, 2012 7:01 AM
    Thursday, October 18, 2012 4:29 PM
  • You can use DateTime.TryParse or TryParseExact (if you know the format of the incoming DateTime Value).

    object dateTimeValue = GetDateTimeValueFromDB();
    DateTime dt;
    
    if(!DateTime.TryParse(Convert.ToString(dateTimeValue), out dt))
    {
        //Value is not in valid DateTime format
    }
    else
    {
        //dt containes DateTime value
    }
     

    I hope this helps.

    Please mark this post as answer if it solved your problem. Happy Programming!

    • Proposed as answer by Norkk Thursday, October 18, 2012 4:31 PM
    • Marked as answer by Bob Shen Tuesday, October 23, 2012 7:01 AM
    Thursday, October 18, 2012 4:31 PM