We help IT Professionals succeed at work.

Retrieve Client's Date & Time

Ray Turner
Ray Turner asked
on
Is there a way to retrieve the client's date and time using ASP.NET 2.0?
Comment
Watch Question

CERTIFIED EXPERT

Commented:
CERTIFIED EXPERT

Commented:
Commented:
You can use a client script, such as javascript or vbscript, to get the client's datetime and send to server via a variable.
For example

<script language=javascript>
function getDateTime(frmObj)
{
    frmObj.cdatetime.value = new Date().toUTCString(); // Mon, 28 Jan 2008 06:10:54 UTC for exam
}
</script>
...
<form onsubmit="getDateTime(this)">
<input type=hidden name=cdatetime>
</form>

Then parse it at server like this

Dim clientDateTime As System.DateTime = System.DateTime.MinValue;
Dim culture As IFormatProvider = new System.Globalization.CultureInfo("en-US", true)
Try
     clientDateTime = System.DateTime.ParseExact(strD, "ddd, dd MMM yyyy HH:mm:ss 'UTC'", culture)
Catch
End Try

Commented:
Dim strD As String = Request("cdatetime") '^^
Ray TurnerSenior Consultant

Author

Commented:
Gnoon,

I tried your code and it returns a time that is 5 hours ahead of my time.  I was expecting to see the same date and time that is on my PC.

How do I get it to do that?

Commented:
I guess it's converted to UTC while parsing because we does not provide any time zome information in the format for the parsing.
Furthermore, as I see your time zone above it is GMT-05:00. Also, en-US (as we used it for parsing) is GMT-05:00. So, I'm not sure here which one is the cause of 5 hours ahead.

I think it's about DateTimeStyles of parsing. Unfortunately, I do not have the environment to test it.
I think using AssumeLocal option is forcing it to not convert to UTC again (because the javascript already did it).

Try
     clientDateTime = System.DateTime.ParseExact(strD, "ddd, dd MMM yyyy HH:mm:ss 'UTC'", culture, _
                  DateTimeStyles.AssumeLocal)
Catch
End Try
Ray TurnerSenior Consultant

Author

Commented:
Thanks

Explore More ContentExplore courses, solutions, and other research materials related to this topic.