none
C# equiv of isdate?

    Question

  • Hi,

    How do i check if a string contains a valid date?

    Ex, i have a string ="jan 6 15:15", I want to set the year to 2006, but only if it's not already a valid date as is the case.

    so, the resulting string should be "jan 6 2006 15:15". but if the string already has a valid date, ex "jan 7 2005", I don't want to touch it.

    I try to use the datetime.parse inside a try/catch, but i couldn't get it to fail.  It keeps setting the date to now().

    Has anyone done this before?

    Wednesday, February 08, 2006 5:16 AM

Answers

  • If you know the format that it must be in, have a look at the DateTime.ParseExact method, otherwise use the DateTime.Parse overload that accepts a DateTimeStyles value and pass DateTimeStyles.NoCurrentDateDefault.
    Wednesday, February 08, 2006 5:22 AM
    Moderator

All replies

  • If you know the format that it must be in, have a look at the DateTime.ParseExact method, otherwise use the DateTime.Parse overload that accepts a DateTimeStyles value and pass DateTimeStyles.NoCurrentDateDefault.
    Wednesday, February 08, 2006 5:22 AM
    Moderator
  • I did that, but all that did was put 1/1/1 in the date.  I guess i need someone to tell me what the exact syntax should be, since what i tried either put in a current date, if the date string i passed in is not valid, or it puts in 1/1/1 if i use nocurrentdatedefault. 

    There's not enough examples in the doc for me to figure out how to use the formatter the way i need.

    Wednesday, February 08, 2006 5:30 PM
  • If your input is a string, you will probably want to use regular expressions (System.Text.Regularexpressions) to create real DateTime structs (System.DateTime).  You can then manipulate them in whatever way that you need to.
    Friday, February 10, 2006 6:15 PM
  • Can't you use the VB function:

    Microsoft.VisualBasic.isdate()

     

    Friday, February 10, 2006 6:52 PM
  • public static bool IsDate(Object obj)
    {
         string strDate = obj.ToString();
         try
          {
                DateTime dt = DateTime.Parse(strDate);
                if(dt != DateTime.MinValue  && dt != DateTime.MaxValue)
                      return true;
                return false;
           }
           catch
            {
                   return false;
             }
    }
    Saturday, February 11, 2006 4:35 AM
  • That works.  THanks!
    Monday, February 13, 2006 7:52 PM
  • It is best to use DateTime.TryParse instead of DateTime.Parse if you are just catching and ignoring the exception. Throwing exceptions via DateTime.Parse is a magnitude slower than using DateTime.TryParse, especially if you using this in a loop.

    • Proposed as answer by Jelly_Yan Friday, November 26, 2010 9:19 AM
    Monday, February 13, 2006 8:25 PM
    Moderator
  • Yes, but be mindful that TryParse is only available in asp.net 2.0.
    Tuesday, July 25, 2006 12:10 AM
  • Not that I'm beating on a dead horse, but in .Net 2.0 you can use Microsoft.VisualBasic.Information.IsDate().
    Thursday, August 10, 2006 12:29 AM
  • It might be overkill to load the VisualBasic assembly for just that one method, but if you find a need for more than a couple of the VisualBasic namespace methods that don't have direct equivalents in C#, there's nothing wrong with using that (extremely) well-tested assembly.  There's such a stigma against it, but I've even seen some people recommend using other far more obscure assemblies (shareware, code from someone's blog, etc.) rather than reference the VisualBasic one.  For example, the Financial methods are very useful - why reference a third-party tool or write your own if the Financial class has very solid methods tested by far more developers than that third-party tool?

    Certainly, you shouldn't reference the namespace for things like "Len" or "Left" - these have obvious .NET equivalents.  But for more complex methods that don't have non-VisualBasic equivalents, I don't see a problem.

    In summary, Microsoft.VisualBasic.dll is just another useful assembly that you have at your disposal.  Don't dismiss it just because it has (gasp) "VisualBasic" in it's name.

    Also note that Microsoft.VisualBasic.dll is not the VB 'compatibility' dll that you certainly should avoid.

    David Anton
    www.tangiblesoftwaresolutions.com
    Instant C#: VB to C# converter
    Instant VB: C# to VB converter
    Instant C++: C# to C++ converter, VB to C++ converter
    Clear VB: Cleans up VB code
    C# Code Metrics: Quick metrics for C#

    Thursday, August 10, 2006 3:02 PM
  • This is the code for the IsDate function that come with Microsoft.VisualBasic assembly. I got this code through reflector utility. I know that I am posting this reply after long time.

    public static bool IsDate(object Expression)
    {
          if (Expression != null)
          {
                if (Expression is DateTime)
                {
                      return true;
                }
                if (Expression is string)
                {
                      try
                      {
                            DateTime time1 = DateType.FromString((string) Expression);
                            return true;
                      }
                      catch (Exception)
                      {
                      }
                }
          }
          return false;
    }
    
    Wednesday, January 03, 2007 8:51 PM
  •  

    In ASP.NET, when you use

    DateTime.TryParse()

    The 2nd parameter is a DateTime output parameter that will be set to the converted date if possible;

    if not possible, will be set to DateTime.MinDate;

    That's all !!!

     

     

     

    Friday, January 26, 2007 4:44 PM
  • These posts were extremely helpful when trying to find the most efficient way to validate a date. But since we are in the dark ages and not using 2.0 framework, let alone 3.0 that is now out, I used the date.parse method. As far as adding another VB assembly from 6.0, well... that's probably not necessary since the any of the other above scenaries will work just fine, but to each his own. Anyway, I hope to post a pretty neat regex validator for dates in the future. Hopefully I can copy one that someone else has taken the time to write, but no such luck just yet.

     

    Wednesday, August 08, 2007 10:22 AM
  • I tried using this:

     

    public static bool IsDate(Object obj)  
        {  
            string strDate = obj.ToString();  
            try  
            {  
                DateTime dt = DateTime.Parse(strDate);  
                if (dt != DateTime.MinValue && dt != DateTime.MaxValue)  
                    return true;  
                return false;  
            }  
            catch (Exception ex)  
            {  
                  
                throw ex;  
                return false;  
            }  
        } 

    .Parse crashes with the following exception:
    {"String was not recognized as a valid DateTime."}

    What is the point of that? We were trying to ascertain it the date was valid.

    Tuesday, September 09, 2008 2:34 PM
  • Try the following instead:

    public static bool IsDate(Object obj) 
        {
            string strDate = obj.ToString();
            try
            {
                DateTime dt;
                DateTime.TryParse(strDate, out dt);
                if (dt != DateTime.MinValue && dt != DateTime.MaxValue)
                    return true;
                return false; 
            }
            catch
            {
                return false;
            }
        }
    Tuesday, February 23, 2010 10:46 PM
  • public bool isDate( string value )
    {
      DateTime date;
      return DateTime.TryParse(value, out date);
    }
    
    Wednesday, September 22, 2010 3:14 AM
  • Using...

    DateTime date;
    return DateTime.TryParse(value, out date);

     

    does not work, it returns false for valid dates.  When I test with the string value "07242011" which is a valid date this returns false. Is there a way to be able to know if a string is a valid date regardless of format used? If the value was "", " ", "00000000", or other bogus data I would expect false.

    Saturday, November 19, 2011 12:41 AM