Format Date column in XML string in ASP.Net using C# and VB.Net

Waghmare
 
on Mar 24, 2021 10:59 PM
Sample_477481.zip
2500 Views

Hi Team,

I have formatted XML string where it contains created date column date and time.

I want to show only date in it.

I want replace date format with dd-MMM-yyyy only.

<note>
<Name>Jani</Name>
<Created_date>20-01-2021 16:25:12</Created_date>
</note>

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 26, 2021 04:13 AM
on Jan 04, 2022 10:48 AM

Hi Waghmare,

Read the xml string and convert the Created_date value to the required format.

Refer below example.

Namespaces

C#

using System.Globalization;
using System.Xml;

VB.Net

Imports System.Globalization
Imports System.Xml

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    string xml = "<note><Name>Jan</Name><Created_date>20-01-2021 16:25:12</Created_date></note>";
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    string xpath = "note/Created_date";
    var nodes = doc.SelectNodes(xpath);
    foreach (XmlNode node in nodes)
    {
        node.InnerText = DateTime.ParseExact(node.InnerText, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd-MMM-yyyy");
    }
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + doc.OuterXml + "')", true);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim xml As String = "<note><Name>Jan</Name><Created_date>20-01-2021 16:25:12</Created_date></note>"
    Dim doc As XmlDocument = New XmlDocument()
    doc.LoadXml(xml)
    Dim xpath As String = "note/Created_date"
    Dim nodes = doc.SelectNodes(xpath)
    For Each node As XmlNode In nodes
        node.InnerText = DateTime.ParseExact(node.InnerText, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd-MMM-yyyy")
    Next
    ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('" & doc.OuterXml & "')", True)
End Sub

Screenshot