Tuesday, June 29, 2010

Retrieve Client Date time using asp.net, C#

Get Client side date and time using asp.net C# code behind.
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx.cs" Inherits="Default6" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
   
<form id="theForm" runat="server">

<div align="center">

   <input type="hidden"  name="cltOffset" id="cltOffset" runat="server" />

  

</div>
    </form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class Default6 : System.Web.UI.Page
{
    DateTime utcDate, localDate;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // set startup script to get client utc offset
            string sname = "getClientUtcOffset";
            Type stype = this.GetType();
            string sliteral = "var now = new Date ( );";
            sliteral += "document.theForm.cltOffset.value = now.getTimezoneOffset ( ) / 60 * ( -1 );";
            sliteral += "document.theForm.submit ( );";

            // register startup script
            ClientScriptManager cs = Page.ClientScript;
            if (!cs.IsStartupScriptRegistered(sname))
                cs.RegisterStartupScript(stype, sname, sliteral, true);
        }
        // get server time zone and utc date
        utcDate = TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now);
        // set client date based on utc + offset
        localDate = utcDate.AddHours(Convert.ToInt32(Request.Form["cltOffset"])); ;
        //Response.Write(cltOffset.Value +"<br>");
        Response.Write(localDate.ToString());
    
    }

}

No comments: