?
Solved

Validating Dates and Times

Posted on 2011-04-20
16
Medium Priority
?
445 Views
Last Modified: 2012-06-27
Hi, I'm using VB.NET2010, WinForms. I have a series of dates and time values that I read in from a text file. I parse them and then I do some calculations with them. -- All that is OK.

However, I had one date that was 05/D/2010...obviously, that was some sort of glitch in my text file, but that still was a problem. I'd like to make sure my dates are really dates and my time values are really time values.

My formats are as follows:

Date:  MM/dd/yyyy
Time:  hh:mm:ss tt

Here is some sample data for each.

Dates:
7/1/2009
7/1/2009
7/1/2009
7/20/2009
8/4/2009
8/4/2009
8/4/2009
8/4/2009
8/4/2009
8/5/2009
11/17/2008
11/17/2008
4/28/2009
11/17/2008
11/13/200


Times:
9:34:06 AM
9:38:58 AM
9:35:34 AM
12:45:01 PM
9:06:27 AM
1:53:48 PM
4:11:11 PM
4:14:12 PM
4:30:39 PM
9:45:12 AM
8:57:12 AM
8:58:51 AM
9:24:06 PM
2:40:58 PM
8:48:34 AM

I would like to flag the values that are invalid, perhaps something like this:

If Not Date.value is valid date Then
   Replace the date value with a date of "99/99/9999" (or something similar)
Endif

Same for the time value.

Or is there a better way?

Thanks for the help,
Fulano
0
Comment
Question by:Mr_Fulano
  • 6
  • 5
  • 3
  • +2
16 Comments
 
LVL 22

Expert Comment

by:danaseaman
ID: 35438523
Try the IsDate Function.
It should work for both dates and times
http://msdn.microsoft.com/en-us/library/00wf8zk9%28v=VS.80%29.aspx
0
 
LVL 9

Expert Comment

by:mayank_joshi
ID: 35438550
you can use  DateTime.TryParseExact method.
e.g:-

Dim enUS As New CultureInfo("en-US") 
Dim dateString As String
Dim dateValue As Date

If DateTime.TryParseExact(dateString, "MM/dd/yyyy", enUS, DateTimeStyles.None, dateValue) Then
   Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,dateValue.Kind)
Else
   Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
End If

Open in new window

0
 
LVL 9

Expert Comment

by:mayank_joshi
ID: 35438564
for time you can use:-

Dim enUS As New CultureInfo("en-US") 
Dim dateString As String
Dim dateValue As DateTime

If DateTime.TryParseExact(dateString, "h:mm:ss tt", enUS, DateTimeStyles.None, dateValue) Then
   Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,dateValue.Kind)
Else
   Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
End If

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 9

Expert Comment

by:mayank_joshi
ID: 35438600
i have designed two functions which can meet your requirement:-

  Function getdate(ByVal datestring As String) As String
        Dim enUS As New CultureInfo("en-US")
        Dim dateValue As DateTime

        If DateTime.TryParseExact(dateString, "M/d/yyyy", enUS, DateTimeStyles.None, dateValue) Then
            Return datestring
        Else
            Return "Invalid Date"
        End If
    End Function

    Function gettime(ByVal timestring As String) As String
        Dim enUS As New CultureInfo("en-US")
        Dim dateValue As DateTime

        If DateTime.TryParseExact(timestring, "h:mm:ss tt", enUS, DateTimeStyles.None, dateValue) Then
            Return timestring
        Else
            Return "Invalid Time"
        End If
    End Function

Open in new window

0
 
LVL 9

Expert Comment

by:mayank_joshi
ID: 35438662
I think following should be better from my earlier comments:-

 Function getdate(ByVal datestring As String) As String
        Dim enUS As New CultureInfo("en-US")
        Dim dateValue As DateTime

        If DateTime.TryParseExact(dateString, "M/d/yyyy", enUS, DateTimeStyles.None, dateValue) Then
            Return Format(dateValue, "M/d/yyyy")
        Else
            Return "Invalid Date"
        End If
    End Function

    Function gettime(ByVal timestring As String) As String
        Dim enUS As New CultureInfo("en-US")
        Dim dateValue As DateTime

        If DateTime.TryParseExact(timestring, "h:mm:ss tt", enUS, DateTimeStyles.None, dateValue) Then
            Return Format(dateValue, "h:mm:ss tt")
        Else
            Return "Invalid Time"
        End If
    End Function

Open in new window

0
 
LVL 2

Expert Comment

by:kambleamar
ID: 35438846
Sub CheckDate()  

02         Dim txtDate As Date = "Dec 26,2009"

03       'can pass txtdate as value in the textbox  

04         If IsDate(txtDate) Then

05            'returns true if valid date  

06             MessageBox.Show("Valid Date")  

07         Else

08             'returns false in case of invalid date  

09             MessageBox.Show("Not a Valid Date")  

10         End If

11     End Sub
0
 

Author Comment

by:Mr_Fulano
ID: 35445411
Hi kambleamar, I like your approach, because its simple, but there is no "IsTime", so I have only half a solution.

Thanks,
Fulano
0
 
LVL 22

Expert Comment

by:danaseaman
ID: 35445414
Try the IsDate Function.
It should work for both dates and times
http://msdn.microsoft.com/en-us/library/00wf8zk9%28v=VS.80%29.aspx
0
 

Author Comment

by:Mr_Fulano
ID: 35445431
Hi mayank_joshi, thank you...a lot of good work. I like the Function approach, but I'm getting an error when I try to process the date into a datatable. I think I may not be able to do what I invisioned.  

dataTableDevices.Columns.Add("DATE_USED", Type.GetType("System.DateTime"))
dataTableDevices.Columns.Add("ACCESS_TYPE", Type.GetType("System.String"))

row("DATE_USED") = getdate(values(4))
row("ACCESS_TYPE") = gettime(values(5))


Error >>> The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.Couldn't store <Invalid Date> in DATE_USED Column.  Expected type is DateTime.

I think we're testing for a valid date and time, but I think when I find an invalid one, it goes bad.

Thanks,
Fulano
0
 

Author Comment

by:Mr_Fulano
ID: 35445725
*************************
     ******   NOTE *******
*************************

Let me restate what it is that I need...so we don't get confused. I have a comma delimited text file that I parse and put into a dataTable. I have the following two lines of code in my project.

dataTableDevices.Columns.Add("DATE_USED", Type.GetType("System.DateTime"))
dataTableDevices.Columns.Add("ACCESS_TYPE", Type.GetType("System.String"))

If I hit a date value that is really not a date or a time value that is not valid. My code aborts. I can stop that by using a Try Catch Fail statement, but I also need to flag the bad date or time. So, I'm trying to validate them as being valid values.

Maybe that helps clear up my question.

Any suggestions on how to do that?

Fulano
0
 

Author Comment

by:Mr_Fulano
ID: 35445733
Hi danaseaman, yes...I agree that the IsDate function works and I didn't know it worked for time values as well, but what happens when it fails the test? What happens when you hit a date like 05/DC/2010. What does it do then? Can I make it replace the value for  05/00/2010, so that I know that was not a valid date.

Thanks,
Fulano
0
 
LVL 9

Expert Comment

by:mayank_joshi
ID: 35446799
the problem is that you are storing the values returned from the getdate function into  a datatime field in datatable.So the value returned must be a valid datetime.Incase of invalid date the string returned is "Invalid Date" which cannot be stored in a datetime field in datatable.A work around is to return a very old date (e.g., 01/01/1900) in case of invalid date.Then whenever you find 01/01/1900 you will know that its some invalid date.The function gettime need not to be changed because you are storing the value returned by it in a string field in datatable.
The new getdate function should be:-

Function getdate(ByVal datestring As String) As Datetime
        Dim enUS As New CultureInfo("en-US")
        Dim dateValue As DateTime

        If DateTime.TryParseExact(dateString, "M/d/yyyy", enUS, DateTimeStyles.None, dateValue) Then
            Return dateValue
        Else
            Return CDate("01/01/1900")
        End If
End Function

Open in new window

 
0
 
LVL 22

Expert Comment

by:danaseaman
ID: 35446848
Try this. SHould work for both dates and times; Returns 0 (CDate("30/12/1899") for invalid date or time.
Function getdate(ByVal datestring As String) As Datetime
   If IsDate(datestring) Then
      Return CDate(datestring)
   Else
      Return 0 'CDate("30/12/1899")
    End If
End Function

Open in new window

0
 
LVL 9

Expert Comment

by:mayank_joshi
ID: 35447855
if want to match the exact format (e.g., "M/d/yyyy" or "MM/dd/yyyy" ) use DateTime.TryParseExact
method .otherwise if you only want to know whether the string is a valid datetime (in any format)
you may use IsDate or DateTime.TryParse

e.g. of DateTime.TryParse:-

Function getdate(ByVal datestring As String) As Datetime
        Dim dateValue As DateTime
        DateTime.TryParse(dateString, dateValue) 
        Return dateValue     
End Function

Open in new window


for invalid dates this function will return Date.MinValue.It Represents the smallest possible value of DateTime ( 01/01/0001)

0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 2000 total points
ID: 35448665
In the code where you are adding the date to the datatable(via a datarow), try this

Try
  drow("Date_Used") = thedatevalue
Catch
  drow("Date_Used")=Date.Parse("01/01/1900")
  LogWrongDate(thedatevalue)
End Try
0
 

Author Closing Comment

by:Mr_Fulano
ID: 35454728
Thank you to all...this was the best solution for my application.

However, thank you to those of you that tried to help with Functions, which was also a good approach.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question