Saturday, 16 March 2013

Check that string format date is in specific date format or not and create date time object of string date in ASP.Net

There are situations where we had date in string format in string variable and want to check that this string contains specific date format or not and if this date is in pacific format, then convert it to date time object.

By checking this, we can avoid any date time conversion run time errors. We can do this using "TryParseExact" method of "DateTime" Class.

Here is an Example for this.

In this example we take one string format date in variable "strDate", and we want trying to parse with date format "dd/MM/yyyy".

When we set strDate variable value to "20/12/2013", at this time this TryParseExact function successfully parse date time, return true and create date time object.

When we set strDate variable value to "12/20/2013", at this time this TryParseExact function does not parse date time, return false and does not create date time object.

In this example we are using "System.Globalization" namespace.
You can use any date format according to your requirement.

C#. Net Example :
        String strDate="12/20/2013";
        string strFormat="dd/MM/yyyy";
        DateTime objDT;

        if (DateTime.TryParseExact(strDate, strFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out objDT) == true)
            Response.Write("<b>Formatted DateTime : </b>" + objDT.ToString());
            Response.Write("<b>Not able to parse datetime.</b>");

VB.Net Examples :
        Dim strDate As String = "20/12/2013"
        Dim strFormat As String = "dd/MM/yyyy"
        Dim objDT As DateTime

        If DateTime.TryParseExact(strDate, strFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, objDT) = True Then
            Response.Write("<b>Formatted DateTime : </b>" & objDT.ToString())
            Response.Write("<b>Not able to parse datetime.</b>")
        End If

Output (Success) :

Parse Date Time

Output (Fail) : 

Parse Date Time

For more Beginning .Net articles visit this link.  Click Here...

Note : Give us your valuable feedback in comments. Give your suggestions in this article so we can update our articles according to that.

No comments:

Post a Comment