JavaScript Get Server Time

I once needed to check time on both server side and in JavaScript, but my problem was that the server was not in the same location I was testing my website so the JavaScript time and Server time in code behind did not match. Below is an easy way I used to go around this issue:

 

HTML PAGE / JavaScript:

<script type=”text/javascript”>

$(document).ready(function() {

var d = new Date();
var dateFromServer = $(‘#<%= lbl_serverTime.ClientID %>’).html(); //Get Time from Label which is loaded from Server (through Code Behind)
var time = dateFromServer.substring(11); //Takes only the time in hh:mm:ss format
var n = (d.getMonth()+1) + “/” + d.getDate() + “/” + d.getFullYear() + ” ” + time ;  //puts it together in MM/dd/yyyy hh:mm:ss format
var dateNow = new Date(n); //Created new date from Server Time

alert(dateNow);

});

</script>

 

<asp:Label ID=”lbl_serverTime” runat=”server” Text=””></asp:Label>

 

CODE BEHIND:

//Copy the method Page_Init in your code behind or add it to your Page_Init Method

protected void Page_Init(object sender, EventArgs e)
{

try
{

lbl_serverTime.Text = DateTime.Now.ToString(); //Sets Label to DateTime which is taken from Server

}
catch (Exception ex)

{

throw ex;

}

}

Javascript pass arguments to WebMethod in C#

So, as we all know WebMethod generally cannot access any other parts of the code since it is normally a static and a web method. Therefore I found a quick and silly idea to get around with this. I have set labels hiden in the page and I’m passing their content as an argument when calling the WebMethod. This is done as shown below through Ajax Calls:

HTML PAGE:

<script type=”text/javascript”>

$(document).ready(function() {

$.ajax({
type: “POST”,
url: “default.aspx/GetMyWebMethod”,
data: “{arg1:'” + $(‘#<%= lbl_myFirstArgument.ClientID %>’).html() + “‘,arg2:'” + $(‘#<%= lbl_mySecondArgument.ClientID %>’).html() + “‘}”,

contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: function(msg) {
//Do something on success
}

});

});

</script>

 

<div style=”display: none”>

<asp:Label ID=”lbl_myFirstArgument” runat=”server” Text=””></asp:Label>
<asp:Label ID=”lbl_mySecondArgument” runat=”server” Text=””></asp:Label>

</div>

 

CODE BEHIND:

//We will fill the content of the labels in the Page_Init in order to be ready on document.ready(function() {} );

protected void Page_Init(object sender, EventArgs e)
{

lbl_myFirstArgument.Text = DateTime.Now.toString();

lbl_mySecondArgument.Text = “Write Something here or get something dynamically from Database to pass to WebMethod”;

}

[WebMethod]
public static void GetMyWebMethod(string arg1, string arg2)
{

//You Can do something with arg1 and arg2 

}

 

That’s All !!!! Please feel free to comment or give suggestions on quick and easy alternatives 🙂