代码之家  ›  专栏  ›  技术社区  ›  Arief

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

  •  23
  • Arief  · 技术社区  · 16 年前

    当我使用 DateTime.Now 我从服务器的角度获取日期和时间。有什么办法可以拿到那张票吗 客户 ASP.NET中的日期和时间?

    6 回复  |  直到 6 年前
        1
  •  16
  •   Ryan    10 年前

    我喜欢使用浏览器/系统时区或让他们选择自己的时区。在过去的一个项目中,我使用了如下内容:

    <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>
    

    然后在服务器上:

    /// <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;
    }
    

    或者,您可以将其作为URL参数传入,并在页面加载中进行处理:

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

    记住使用分钟,因为并非所有时区都是整小时。

        2
  •  12
  •   Simon Johnson Andomar    16 年前

    我要做的是创建一个隐藏的输入字段,然后将Javascript例程连接到表单的onsubmit事件。此例程将使用客户端计算机上的时间填充隐藏字段。

    隐藏字段可以通过使用HTML控件“HtmlInputHidden”类与ASP.NET一起使用。您只需给输入控件一个runat=“server”属性,就像任何其他服务器端控件一样。

    或者,您可以使用AJAX实现这一点,但实现将取决于您使用的库。

        3
  •  5
  •   Stephen Wrighton    16 年前

    如果您正在维护用户配置文件,您可以让他们告诉您他们的时区,然后进行必要的计算。

        4
  •  0
  •   Keltex    16 年前

    另一种方法是根据用户的IP地址对其进行地理定位。或者,如果浏览器具有此功能,则进行地理定位(Firefox即将推出)。一旦你有了用户的位置,你就可以查找时区了。

    javascript解决方案可能是一个好的、简单的解决方案。

        5
  •  0
  •   JacquesB    16 年前

    客户机和服务器可能没有完全同步,因此问题是您是想要客户机上的时间,还是想要服务器上的时间,但要根据时区差异进行调整。Javascript可以获取客户端上的时间(包括时区)。您还可以将服务器上的时间与客户端的时区相结合。

    不过,你永远无法获得比请求延迟更高精度的时间。

        6
  •  -5
  •   Siddharth Rout    12 年前

    Dim strLanguage As String = Request.UserLanguages(0)
    Dim currentCulture As CultureInfo = CultureInfo.CreateSpecificCulture(strLanguage)
    Dim dateformat As String = currentCulture.DateTimeFormat.ShortDatePattern
    

    这将生成查看数据的计算机的数据时间格式。