Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...