如何在asp.net中获取客户端的当前日期和时间? [英] How to get client current date and time in asp.net?

查看:232
本文介绍了如何在asp.net中获取客户端的当前日期和时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主页上有一个隐藏字段.然后,我使用Javascript将当前日期和时间设置为该隐藏字段"中的值.我无法在其他任何页面的页面加载方法中获得此隐藏字段的值.

I have a hidden field in my master page. And I set the current date and time as a value in that "hiddenfield" using Javascript. I am unable to get this hidden field value in any other page's page load method.

这是我的代码.

HiddenField hdnCurrentDate = (HiddenField)this.Master.FindControl("hdnCurrentDate");
                ClientScript.RegisterClientScriptBlock(this.GetType(), "Message", "var CurrentDate = new Date(); $('#" + hdnCurrentDate.ClientID + "').val(CurrentDate);alert($('#ctl00_hdnCurrentDate').val());", true);

我已经在母版页中定义了Hiddenfield,

I have defined Hiddenfield in master page like

<asp:HiddenField ID="hdnCurrentDate" runat="server" />

我收到"hdnCurrentDate"的警报未定义.这是因为我在页面加载中使用了非回发方法编写了代码.

I got the alert of "hdnCurrentDate" is undefined. This is because I wrote the code in page load in not post back method.

这是我实现的另一种方式.

Here is the other way what I have implemented.

我在后面的代码中使用了ConvertTimeBySystemTimeZoneId.这是相同的代码.

I have used ConvertTimeBySystemTimeZoneId in code behind. Here is the code for the same.

DateTime ClientDateTime = DateTime.Now;
        DateTime _localTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(ClientDateTime, "Arab Standard Time");
        return _localTime;

我没有获得目的地时区ID,而是阿拉伯标准时间".如果我能解决,我的问题将得到解决.

I didn't get destination time zone ID instead of "Arab standard Time". If I will get it, my problem will be solved.

还有其他方法可以获取我页面中任何日期的当前日期时间.我不想使用会话和cookie.

Is there any other way to get the current date time in any of my page. I don't want to use Session and cookies.

谢谢.

推荐答案

以下是获取客户端当前日期时间的javascript函数:

Below is the javascript function to get client current datetime:

<script type="text/javascript">
function GetDate(date) {
    CurTime = new Date(date);
    var offset = (new Date().getTimezoneOffset() / 60) * (-1);
    var utc = CurTime.getTime() + (offset * 60000 * (-1));
    var serverDate = new Date(utc + (3600000 * offset));
    var dateString = (serverDate.getMonth() + 1) + "/" + serverDate.getDate() + "/" +     
serverDate.getFullYear() + " " + serverDate.toLocaleTimeString("en-US", { hour12: true });
}
</script>

您还可以从下面的代码中获取抵消时间":

You can also get OffSet Time from code behind as below:

public static TimeSpan GetOffSetTime(string date)
    {
        DateTime d = Convert.ToDateTime(date);
        TimeZone zone = TimeZone.CurrentTimeZone;
        TimeSpan local = zone.GetUtcOffset(d);
        return local;
    }

这篇关于如何在asp.net中获取客户端的当前日期和时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆