Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

c# - How to get client current date and time in asp.net?

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.

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

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

Here is the other way what I have implemented.

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;

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

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.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...