Saturday, 13 April 2013

Beginning .Net : Convert or Cast from one date format to another date format in ASP.Net With C#.Net and VB.Net Examples

You can easily do date time conversion in ASP.Net. You can convert date time from one format to other format.

In real application when data comes from external sources at that time chances increase for date time conversion error because both sender and receiver of data has different local date format setting.

May be you want to display or store date time in different format. If you know that date format that come from outside and you need in different format at that time your task become easy.

Here is example for this.
In this, we have one date in string variable in "MM/dd/yyyy" format. Now we convert this date in "dd/MM/yyyy" format. We are using "TryParseExact" method to parse and create DateTime object from date string after that, we convert in our desire format using "ToString" method. You can convert in any date time format.

C#. Net Example :
        String origionalDate = "12/20/2013"; // Format : MM/dd/yyyy
        string origionalFormat = "MM/dd/yyyy";
        string convertInToFormat="dd/MM/yyyy";
        String convertedDate;
        DateTime objDT;

        if (DateTime.TryParseExact(origionalDate, origionalFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out objDT) == true)
            convertedDate = objDT.ToString(convertInToFormat);
            Response.Write("<b>Original DateTime Format ( " + origionalFormat + " ) : </b>" + origionalDate);
            Response.Write("<b>Converted DateTime Format ( " + convertInToFormat + " )  : </b>" + convertedDate);
            Response.Write("<b>Not able to parse datetime.</b>");

VB.Net Examples :
        Dim origionalDate As [String] = "12/20/2013" ' Format : MM/dd/yyyy
        Dim origionalFormat As String = "MM/dd/yyyy"
        Dim convertInToFormat As String = "dd/MM/yyyy"
        Dim convertedDate As [String]
        Dim objDT As DateTime

        If DateTime.TryParseExact(origionalDate, origionalFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, objDT) = True Then
            convertedDate = objDT.ToString(convertInToFormat)
            Response.Write("<b>Original DateTime Format ( " & origionalFormat & " ) : </b>" & origionalDate)
            Response.Write("<b>Converted DateTime Format ( " & convertInToFormat & " )  : </b>" & convertedDate)
            Response.Write("<b>Not able to parse datetime.</b>")
        End If

Output :

Date Time Conversion In ASP.Net

No comments:

Post a Comment