C# 如何在asp.net中获取客户端当前日期和时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13717479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get client current date and time in asp.net?
提问by Azhar Mansuri
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.
我的母版页中有一个隐藏字段。我使用 Javascript 将当前日期和时间设置为“隐藏字段”中的一个值。我无法在任何其他页面的页面加载方法中获取此隐藏字段值。
Here is my code.
这是我的代码。
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);
I have defined Hiddenfield in master page like
我在母版页中定义了 Hiddenfield,例如
<asp:HiddenField ID="hdnCurrentDate" runat="server" />
I got the alert of "hdnCurrentDate" is undefined. This is because I wrote the code in page load in not post back method.
我收到“hdnCurrentDate”未定义的警报。这是因为我在页面加载中使用 not post back 方法编写了代码。
Here is the other way what I have implemented.
这是我实施的另一种方式。
I have used ConvertTimeBySystemTimeZoneId in code behind. Here is the code for the same.
我在后面的代码中使用了 ConvertTimeBySystemTimeZoneId。这是相同的代码。
DateTime ClientDateTime = DateTime.Now;
DateTime _localTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(ClientDateTime, "Arab Standard Time");
return _localTime;
I didn't get destination time zone ID instead of "Arab standard Time". If I will get it, my problem will be solved.
我没有得到目的地时区 ID 而不是“阿拉伯标准时间”。如果我得到它,我的问题就会解决。
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.
有没有其他方法可以在我的任何页面中获取当前日期时间。我不想使用 Session 和 cookie。
Thanks in advance.
提前致谢。
采纳答案by Shreya
Below is the javascript function to get client current datetime:
下面是获取客户端当前日期时间的 javascript 函数:
<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;
}
回答by sajanyamaha
'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.'In that caseyou can use JavaScript
'有没有其他方法可以在我的任何页面中获取当前日期时间。我不想使用 Session 和 cookie。在这种情况下,您可以使用 JavaScript
Also, you don't need to use RegisterStartupScript. You can just call the GetDate()function in the onLoadevent.
此外,您不需要使用RegisterStartupScript. 您可以GetDate()在onLoad事件中调用该函数。
<script type="text/javascript">
window.onload = function(){
getDate();
};
function GetDate()
{
var dt = new Date();
var element = document.getElementById("MainContent_FormView1_Label1");
element.text = dt.toDateString();
}
</script>
However, you might want to read this SO threadfor best practice in using window.onload, or consider using a framework such as jQueryand its document.ready
但是,您可能希望阅读此 SO 线程以获取使用 的最佳实践window.onload,或者考虑使用诸如jQuery 之类的框架及其document.ready
回答by sreejithsdev
Master Page
母版页
set servertime
设置服务器时间
<asp:hiddenfield runat="server" id="HiddenField1"></asp:hiddenfield>
protected void Page_Load(object sender, EventArgs e)
{
HiddenField1.Value = DateTime.Now.ToString();
}
set client machine time
设置客户端机器时间
<script type="text/javascript">
function setvalue() {
document.getElementById('HiddenField1').value = new Date();
}
</script>
<body onload="setvalue();">
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="HiddenField1" runat="server"/>
</div>
</form>
</body>
Content Page
内容页
HiddenField hdnvalue = this.Master.Master.FindControl("HiddenField1") as HiddenField;
string currenttime=hdnvalue.Value;
回答by Arshad
I have done this by using following way:
我通过使用以下方式做到了这一点:
I have taken a
HiddenFieldinto the previous page where it requires :<asp:HiddenField ID="hdnTimeOffset" ClientIDMode="Static" runat="server" Value="" />Then, I am getting browser timezone by this :
$(document).ready(function () { var offset = new Date().getTimezoneOffset(); $('#hdnTimeOffset').val(offset); });I am getting time zone into a
Sessionvariable of the previous page, before redirecting to the next page, like on button click:protected void btn_Click(object sender, EventArgs e) { Session["TimeOffset"] = hdnTimeOffset.Value; Response.Redirect("~/Root/abc.aspx"); }In the Main Page, I get the current time by using following code :
DateTime dtmCurrentDateTime = DateTime.Now.ToUniversalTime(); double dblMinutes =Convert.ToDouble(Session["TimeOffset"].ToString()); dtmCurrentDateTime = dtmCurrentDateTime.AddMinutes(-dblMinutes);
我已经
HiddenField进入了上一页,它需要:<asp:HiddenField ID="hdnTimeOffset" ClientIDMode="Static" runat="server" Value="" />然后,我通过这个获取浏览器时区:
$(document).ready(function () { var offset = new Date().getTimezoneOffset(); $('#hdnTimeOffset').val(offset); });Session在重定向到下一页之前,我将时区放入上一页的变量中,例如单击按钮:protected void btn_Click(object sender, EventArgs e) { Session["TimeOffset"] = hdnTimeOffset.Value; Response.Redirect("~/Root/abc.aspx"); }在主页中,我使用以下代码获取当前时间:
DateTime dtmCurrentDateTime = DateTime.Now.ToUniversalTime(); double dblMinutes =Convert.ToDouble(Session["TimeOffset"].ToString()); dtmCurrentDateTime = dtmCurrentDateTime.AddMinutes(-dblMinutes);
回答by Amarnath Balasubramanian
modified code from This link:
<script type="text/javascript">
function getDateTime()
{
var localTime = new Date();
var year= localTime.getYear();
var month= localTime.getMonth() +1;
var date = localTime.getDate();
var hours = localTime .getHours();
var minutes = localTime .getMinutes();
var seconds = localTime .getSeconds();
//at this point you can do with your results whatever you please
}
</script>
At this point i would concatenate all of the fields together and put them in an asp:HiddenField control so they can be read on the server. On the server, call Convert.ToDateTime() on the Text value of your HiddenField.
在这一点上,我会将所有字段连接在一起并将它们放在一个 asp:HiddenField 控件中,以便它们可以在服务器上读取。在服务器上,对 HiddenField 的 Text 值调用 Convert.ToDateTime()。
if you don't use a masterpage you should try this.
如果你不使用母版,你应该试试这个。
HiddenField hdnFieldValue = (HiddenField)PreviousPage.FindControl("hdnField");
Updated:
更新:
Put a hidden field on the page.
在页面上放置一个隐藏字段。
<asp:HiddenField ID="hidChild" runat="server"/>
in your javascript function
在你的 javascript 函数中
var childHidden = document.getElementById('<%hidChild.ClientID%>');
childHidden.value = window.opener.document.getElementById('text1').value;
Now access this hidden control on the page load event.
现在在页面加载事件上访问这个隐藏的控件。
Response.Write(hidChild.Value); or Session["ParentVal"]=hidChild.Value;
回答by Tr??ng Long
How about use CulturalInfo From C# to get it?
如何使用C# 中的CulturalInfo 来获取它?
string currentFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
字符串 currentFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
this will return "dd/MM/yy" or "dd/M/YYY" any format in client
这将在客户端返回“dd/MM/yy”或“dd/M/YYY”任何格式

