Ari*_*ief 24 .net c# asp.net datetime client-side
当我使用时,DateTime.Now
我从服务器的角度来看日期和时间.有没有办法在ASP.NET中获取客户端的日期和时间?
Rya*_*yan 16
我喜欢使用浏览器/系统时间和时区或让他们选择时区的想法.在过去的项目中,我使用了这样的东西:
<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>
Run Code Online (Sandbox Code Playgroud)
然后在服务器上:
/// <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;
}
Run Code Online (Sandbox Code Playgroud)
或者您可以将其作为URL参数传递并在Page_Load中处理:
http://host/page.aspx?tz=-360
Run Code Online (Sandbox Code Playgroud)
只记得使用分钟,因为并非所有时区都是整个小时.
Sim*_*son 11
我要做的是创建一个隐藏的输入字段,然后将Javascript例程连接到表单的onsubmit事件.此例程将使用客户端计算机上的时间填充隐藏字段.
隐藏字段可以通过使用HTML控件"HtmlInputHidden"类与ASP.NET一起使用.您只需为输入控件提供runat ="server"属性,就像任何其他服务器端控件一样.
然后,当表单回发时,服务器可以读出此时间.如果您需要在许多地方执行此操作,您甚至可以将其包装在服务器控件中.
或者,您可以使用AJAX执行此操作,但实现将取决于您使用的库.