Results 1 to 10 of 10

Thread: [RESOLVED] DateTime format validation method using DateTime.TryParse() always returns false??

  1. #1

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Resolved [RESOLVED] DateTime format validation method using DateTime.TryParse() always returns false??

    So, simply put I made a quick method that returns true if a format provided is a valid for a date time to string representation..
    This all seems like it should work to me, and even with some googling I've had no luck.

    The method is..
    Code:
        Private Function ValidateDateTimeFormat(ByVal format As String) As Boolean
            Dim dt As DateTime = DateTime.MinValue
            Dim result As Boolean = False
    
            If DateTime.TryParse(format, dt) Then 'Also tried...and TryParseExact as some forum solutions suggested.
            'If DateTime.TryParse(format, System.Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, dt) Then
                result = True
            End If
            dt = Nothing
            Return result
        End Function
    Results(for me) are...
    yyyy = False
    dddd, MMMM dd, yyyy = False
    etc etc..

    In all honestly I manually set my condition to true and everything displays fine, just as it should. Only when I replace that True with my method does it always returns false, no matter the format provided.



    Thanks in advance
    David Carrigan
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: DateTime format validation method using DateTime.TryParse() always returns false?

    Firstly, do you want to enforce one or more specific formats or do you just want to validate against what's valid on the local machine?
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: DateTime format validation method using DateTime.TryParse() always returns false?

    Right.... because dddd, MMMM dd, yyyy isn't a valid date.... it's a valid FORMAT for a date... but the tryParse takes two parameters... the first is a STRING varaible which contains a date to convert.... the second parameter is where the converted date should go if successfully converted.

    Based on the name of the function and what you're passing in, it sounds like your're trying to validate the format of a date... TryParse parses a date string... not a format string...

    What you probably should do is convert the date to a string using the passed in format, then try to TryParse that result...

    Code:
        Private Function ValidateDateTimeFormat(ByVal format As String) As Boolean
            Dim s As String= DateTime.MinValue.ToString(format) 'Create a Date String using the format passed into the function
            Dim dt As DateTime
            Dim result As Boolean = False
    
            If DateTime.TryParse(s, dt) Then ' Here s is the formatted date, that is what you should be passing in.
                result = True
            End If
            dt = Nothing
            Return result
        End Function
    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  4. #4

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: DateTime format validation method using DateTime.TryParse() always returns false?

    Quote Originally Posted by jmcilhinney View Post
    Firstly, do you want to enforce one or more specific formats or do you just want to validate against what's valid on the local machine?
    I'm actually using this in the set for a property of a control inheriting the Label control. The property is Format, similar to the DateTimePicker controls. I'm only validating whatever the user chooses to pass. If it's not valid then the format doesn't change, error message informs the user the format is invalid etc etc.


    But thank you techgnome, that was it! I honestly cannot believe I made that mistake! You are absolutely right, and my approach never would have worked. kudos, and thanks again.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  5. #5

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: DateTime format validation method using DateTime.TryParse() always returns false?

    Techgnome, I would give you some rep. But apparently you help me to often I guess I'll have to wait someone else to help me before I can give you whats rightfully yours.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  6. #6
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: DateTime format validation method using DateTime.TryParse() always returns false?

    Quote Originally Posted by techgnome View Post
    Right.... because dddd, MMMM dd, yyyy isn't a valid date.... it's a valid FORMAT for a date... but the tryParse takes two parameters... the first is a STRING varaible which contains a date to convert.... the second parameter is where the converted date should go if successfully converted.

    Based on the name of the function and what you're passing in, it sounds like your're trying to validate the format of a date... TryParse parses a date string... not a format string...

    What you probably should do is convert the date to a string using the passed in format, then try to TryParse that result...

    Code:
        Private Function ValidateDateTimeFormat(ByVal format As String) As Boolean
            Dim s As String= DateTime.MinValue.ToString(format) 'Create a Date String using the format passed into the function
            Dim dt As DateTime
            Dim result As Boolean = False
    
            If DateTime.TryParse(s, dt) Then ' Here s is the formatted date, that is what you should be passing in.
                result = True
            End If
            dt = Nothing
            Return result
        End Function
    -tg
    If you're not going to do anything with the result of a .TryParse in VB.NET you can set the result to Nothing rather than creating a temporary variable you need to get rid of.

    vb.net Code:
    1. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    2.         Dim now = DateTime.Now()
    3.  
    4.         Dim format1 = "MM/dd/yyyy"
    5.         Dim format2 = "ab/cd/efgh"
    6.  
    7.         Dim isFormat1Valid = ValidateDateTimeFormat(now, format1)
    8.         Dim isFormat2Valid = ValidateDateTimeFormat(now, format2)
    9.     End Sub
    10.  
    11.     Private Function ValidateDateTimeFormat(dt As DateTime, format As String) As Boolean
    12.         Return DateTime.TryParse(dt.ToString(format), Nothing)
    13.     End Function
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  7. #7
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: DateTime format validation method using DateTime.TryParse() always returns false?

    I assumed that you meant that you were passing date strings in those formats, not the format strings themselves.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  8. #8

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: DateTime format validation method using DateTime.TryParse() always returns false?

    If you're not going to do anything with the result of a .TryParse in VB.NET you can set the result to Nothing rather than creating a temporary variable you need to get rid of.
    Good call on that. Actually up until now I've never considered having Nothing as the return on a .TryParse(). Thanks!
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  9. #9

    Thread Starter
    Hyperactive Member DavesChillaxin's Avatar
    Join Date
    Mar 2011
    Location
    WNY
    Posts
    451

    Re: DateTime format validation method using DateTime.TryParse() always returns false?

    Quote Originally Posted by jmcilhinney View Post
    I assumed that you meant that you were passing date strings in those formats, not the format strings themselves.
    Yup, precisely. In all honesty it's been a rough two weeks for me, now I'm getting sick. My heads' just not in the right place , thanks again.
    Please rate if my post was helpful!
    Per favore e grazie!




    Code Bank:
    Advanced Algebra Class *Update | True Gradient Label Control *Dev | A Smarter TextBox *Update | Register Global HotKey *Update
    Media Library Beta *Dev | Mouse Tracker (Available in VB.net and C#.net) *New | On-Screen Numpad (VB.net) *New

  10. #10
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: DateTime format validation method using DateTime.TryParse() always returns false?

    Quote Originally Posted by DavesChillaxin View Post
    Good call on that. Actually up until now I've never considered having Nothing as the return on a .TryParse(). Thanks!
    It's not that you're using Nothing as the return. The return value is a Boolean regardless. The output parameter is a DateTime. If you pass Nothing to that parameter then, inside the TryParse method, it will receive the default value for the DateTime type, which is #1/01/0001#. If the conversion works then the method will assign the appropriate DateTime value to the parameter and that is what the method outputs. The only difference is that, because you used a literal rather than a variable, you don't have access to that output value.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width