如何在ASP.NET中获取客户端日期和时间?

我使用DateTime.Now服务器时会得到日期和时间。有什么方法可以在ASP.NET中获取客户端日期和时间?



www说
浏览 880回答 3
3回答

叮当猫咪

我喜欢使用浏览器/系统时间和时区或让他们选择其时区的想法。在过去的项目中,我使用了以下内容:<script language="javascript">function checkClientTimeZone(){&nbsp; &nbsp; // Set the client time zone&nbsp; &nbsp; var dt = new Date();&nbsp; &nbsp; SetCookieCrumb("ClientDateTime", dt.toString());&nbsp; &nbsp; var tz = -dt.getTimezoneOffset();&nbsp; &nbsp; SetCookieCrumb("ClientTimeZone", tz.toString());&nbsp; &nbsp; // Expire in one year&nbsp; &nbsp; dt.setYear(dt.getYear() + 1);&nbsp; &nbsp; SetCookieCrumb("expires", dt.toUTCString());}// Attach to the document onload eventcheckClientTimeZone();</script>然后在服务器上:/// <summary>/// Returns the client (if available in cookie) or server timezone./// </summary>public static int GetTimeZoneOffset(HttpRequest Request){&nbsp; &nbsp; // Default to the server time zone&nbsp; &nbsp; TimeZone tz = TimeZone.CurrentTimeZone;&nbsp; &nbsp; TimeSpan ts = tz.GetUtcOffset(DateTime.Now);&nbsp; &nbsp; int result = (int) ts.TotalMinutes;&nbsp; &nbsp; // Then check for client time zone (minutes) in a cookie&nbsp; &nbsp; HttpCookie cookie = Request.Cookies["ClientTimeZone"];&nbsp; &nbsp; if (cookie != null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; int clientTimeZone;&nbsp; &nbsp; &nbsp; &nbsp; if (Int32.TryParse(cookie.Value, out clientTimeZone))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = clientTimeZone;&nbsp; &nbsp; }&nbsp; &nbsp; return result;}或者,您可以将其作为URL参数传递并在Page_Load中进行处理:http://host/page.aspx?tz=-360请记住要使用分钟,因为并非所有时区都是整个小时。
打开App,查看更多内容
随时随地看视频慕课网APP