12/02/2013

How to convert numbers in date format? VB.Net Code for begginers


In this post I would like to write about How to convert the numbers in date format. Converting integers in date format is very easy.Suppose you want to convert a string i.e 12022013 into date the result would be 12/02/2013 (dd/MM/yyyy) for  conversion of string into date format, I will create a function and whenever I need to convert the string into date format I will recall that function. The VB Code for that function will be as under.

'Purpose : This method would convert number format date data into date.
'Parameters : Number format string would be passed. Eg: 12022013
'Return Value : Date. Eg: 12/02/2013
Public Function Number2Date(ByVal lNum As Long) As Date
        Dim strNum As String = CStr(lNum)
        Dim iDay, iMon, iYear As Integer
        Dim ValidDate As Date
         Try
            'If date is not in valid format
            If strNum.Length = 7 Then
                strNum = "0" + strNum
            End If

            iMon = CInt(strNum.Substring(0, 2))
            iDay = CInt(strNum.Substring(2, 2))
            iYear = CInt(strNum.Substring(4, 4))
            ValidDate = New Date(iYear, iMon, iDay)
        Catch ex As Exception
            ex.Message
        End Try
         Return ValidDate
    End Function


No comments:

Post a Comment

What & How