In this article I will explainwith an example, how to get the Server Current Date and Time in ASP.Net using C# and VB.Net.
ASP.Net is Client Server architecture and hence to get the Server Current Date and Time, AJAX and ScriptManager will be used.
 
 
Enabling PageMethods
The first thing you need to do is add a ASP.Net AJAX ScriptManager to the page and set its EnablePageMethods property to true as shown below
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
 
 
HTML Markup
As you noticed I have added a textbox when user can enter his name and a HTML button that calls a JavaScript method to get the Current Time.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server" ></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()"/>
</div>
</form>
 
 
Client Side Method to display Current Date and Time
The ShowCurrentTime method makes an AJAX call to the server using ASP.Net AJAX ScriptManager PageMethods and executes the GetCurrentTime method which accepts the username and returns a string value.
<script type="text/javascript">
function ShowCurrentTime() {
PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>
 
 
Server Side Method to get Current Date and Time
The GetCurrentTime method simply returns a greeting message to the user along with the current server time. An important thing to note is that the method is declared as static (C#) and Shared (VB.Net) and also it is declared as Web Method unless you do this you won’t be able to call the methods using ASP.Net ScriptManager PageMethods.
C#
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}
 
VB.Net
<System.Web.Services.WebMethod()> _
Public Shared Function GetCurrentTime(ByVal name AsString) AsString
Return"Hello "& name & Environment.NewLine &"The Current Time is: "& _
            DateTime.Now.ToString()
EndFunction
 
 
Screenshot
The figure below displays the output displayed to the user when the button is clicked
Get Server Current Date and Time in ASP.Net using C# and VB.Net
 
 
Demo
 
 
Downloads