jQuery to Retrieve Server’s current date and time with ASP.NET

In this post, we will see how to retrieve server's current date and time without using ajax. It's very simple and one line of ASP.NET code can help you to retrieve the server's current date & time. For demo, I have placed a textbox and will fetch the Server's date and time and display it in Textbox.

<asp:TextBox ID="txtValue" runat="server"></asp:TextBox>

See below jQuery code.

$(document).ready(function() {
$('#txtValue').val('<%=(System.DateTime.Now).ToString()%>');
});

It is just a simple ASP.NET code, which we normally write in code behind file.Above code will provide date and time both. If you want to fetch only time, then modify the above jQuery code to below code.

$(document).ready(function() {
$('#txtValue').val('<%=System.DateTime.Now.ToShortTimeString()%>');
});

You can also fetch only the Year, month, day, hours, minutes or seconds. For example, to fetch hours,

$('#txtValue').val('<%=(System.DateTime.Now.Hour).ToString()%>');

To fetch only minutes,

$('#txtValue').val('<%=(System.DateTime.Now.Minute).ToString()%>');

Read more about DateTime.Now on MSDN and find out what more you can achieve using this property.

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...