Create Utility class to validate DateTime in ASP.Net using C# and VB.Net

ramco1917
 
on Oct 02, 2022 11:20 PM
521 Views

Hi

I have below code & i have to write in every program where this check is to be required.

Can i make one Utility so that it can be called from one point. I should not write in each program.

if (txtKRAQ1dt0.Text.Trim() != "")
{
    DateTime PMDate2 = DateTime.ParseExact(txtKRAQ1dt0.Text, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
    KRAdtFrom = Convert.ToDateTime(PMDate2.ToString("yyyy-MM-dd"));
}

Thanks

Download FREE API for Word, Excel and PDF in ASP.Net: Download
Shivam.M
 
on Oct 03, 2022 06:48 AM

Hi ramco1917,

Please refer below sample.

HTML

<asp:TextBox ID="txtKRAQ1dt0" runat="server"></asp:TextBox>
<asp:Button ID="btnValidate" runat="server" Text="Validate" OnClick="Validate"/>

Code

C#

Default

protected void Validate(object sender, EventArgs e)
{
    DateTime kradtFrom = Utility.GetKRAdtFrom(txtKRAQ1dt0.Text);
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + kradtFrom.ToString("dd-MM-yyyy") + "');", true);
}

Utility

public static class Utility
{
    public static DateTime GetKRAdtFrom(string kraValue)
    {
        DateTime KRAdtFrom = new DateTime();
        if (!string.IsNullOrEmpty(kraValue.Trim()))
        {
            KRAdtFrom = DateTime.ParseExact(kraValue, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
        }

        return KRAdtFrom;
    }
}

VB.Net

Default

Protected Sub Validate(ByVal sender As Object, ByVal e As EventArgs)
    Dim kradtFrom As DateTime = Utility.GetKRAdtFrom(txtKRAQ1dt0.Text)
    ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('" & kradtFrom.ToString("dd-MM-yyyy") & "');", True)
End Sub

Utility

Module Utility
    Function GetKRAdtFrom(ByVal kraValue As String) As DateTime
        Dim KRAdtFrom As DateTime = New DateTime()

        If Not String.IsNullOrEmpty(kraValue.Trim()) Then
            KRAdtFrom = DateTime.ParseExact(kraValue, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture)
        End If

        Return KRAdtFrom
    End Function
End Module

Screenshot