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;

}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s