Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get client date and time in ASP.NET?

Tags:

When I use DateTime.Now I get the date and time from the server point of view. Is there any way to get the client date and time in ASP.NET?

like image 600
Arief Avatar asked Nov 08 '08 15:11

Arief


People also ask

How to get client side date time in asp net?

You just give you input control a runat="server" attribute like any other server side control. The server can then read out this time when the form posts back.

How to get the date time of client pc in asp net c#?

On the server, call Convert. ToDateTime() on the Text value of your HiddenField.


1 Answers

I like the idea of either using the browser/system time and time zone or letting them select their time zone. In a past project I used something like this:

<script language="javascript"> function checkClientTimeZone() {     // Set the client time zone     var dt = new Date();     SetCookieCrumb("ClientDateTime", dt.toString());      var tz = -dt.getTimezoneOffset();     SetCookieCrumb("ClientTimeZone", tz.toString());      // Expire in one year     dt.setYear(dt.getYear() + 1);     SetCookieCrumb("expires", dt.toUTCString()); }  // Attach to the document onload event checkClientTimeZone(); </script> 

And then on the server:

/// <summary> /// Returns the client (if available in cookie) or server timezone. /// </summary> public static int GetTimeZoneOffset(HttpRequest Request) {     // Default to the server time zone     TimeZone tz = TimeZone.CurrentTimeZone;     TimeSpan ts = tz.GetUtcOffset(DateTime.Now);     int result = (int) ts.TotalMinutes;     // Then check for client time zone (minutes) in a cookie     HttpCookie cookie = Request.Cookies["ClientTimeZone"];     if (cookie != null)     {         int clientTimeZone;         if (Int32.TryParse(cookie.Value, out clientTimeZone))             result = clientTimeZone;     }     return result; } 

Or you can pass it in as a URL parameter and handle it in the Page_Load:

http://host/page.aspx?tz=-360 

Just remember to use minutes, since not all time zones are whole hours.

like image 200
Ryan Avatar answered Oct 02 '22 00:10

Ryan