Monday, July 04, 2005

Date Validation ,Date Conversion

This Function will take All kind of Date Format and Finally it convert to "MM/DD/YYYY"
 
Format to be Acceptted  mm/dd/yyyy
                                    m/d/yy
                                    mm/dd\yyyy
                                    mm-dd-yyyy
                                    m-d-yyyy   
                                    mm/yyyy   
                                    m/yy     ....etc
 
Function for VB.NET
 

Public Shared Function ConvertToDate(ByVal dateString As String, ByRef result As DateTime) As Boolean

If dateString.Trim = String.Empty Then

Return False

End If

Try

dateString = dateString.Trim

dateString = dateString.Replace("\", "/")

dateString = dateString.Replace(":", "/")

dateString = dateString.Replace("-", "/")

Dim year, month, day As Int16

If dateString.IndexOf("/") = dateString.LastIndexOf("/") Then

' MM/YY format.

Dim index1 As Int16 = dateString.IndexOf("/")

Dim index2 As Int16 = dateString.LastIndexOf("/")

year = dateString.Substring(index2 + 1)

month = dateString.Substring(0, index1)

day = DateTime.DaysInMonth(year, month)

ElseIf dateString.IndexOf("/", dateString.IndexOf("/") + 1) = dateString.LastIndexOf("/") Then ' Check if the second "/" is the last "/"

' MM/DD/YY format.

Dim index1 As Int16 = dateString.IndexOf("/")

Dim index2 As Int16 = dateString.LastIndexOf("/")

year = dateString.Substring(index2 + 1)

month = dateString.Substring(0, index1)

day = dateString.Substring(index1 + 1, index2 - index1 - 1)

Else

Return False

End If

If year < 100 Then

year = year + 2000 ' Convert to 4 digit format.

End If

Dim expDate As String = MonthName(month) & day & ", " & year

If Not IsDate(expDate) Then

Return False

Else

result = CType(expDate, DateTime)

Return True

End If

Catch ex As Exception

Return False

End Try

End Function


Do you Yahoo!?
Yahoo! Mail - Helps protect you from nasty viruses.

No comments: