I have some javascript that only needs to execute if it's been less than so-many-seconds since a date that is calculated on the server, but I'm having some trouble with the date comparison. Here's what I've tried:
<script type="text/javascript">
var elapsedMillis = 10000;
if(Date.now() - <%=(benchmarkDate-new DateTime(1970,1,1)).TotalMilliseconds%> < elapsedMillis)
{
//do stuff
}
</script>
Unfortunately, the C# TimeSpan is giving me a number of milliseconds that varies from JavaScript's Date.now() by about 14,000 seconds even if executed within ten seconds of setting benchmarkDate.
This turned out to be a timezone issue because I didn't realize JavaScript's Date.now() was returning a UTC date. Here's my fix to convert the C# date to UTC first, just in case it helps someone else:
<script type="text/javascript">
var elapsedMillis = 10000;
if(Date.now() - <%=(benchmarkDate.ToUniversalTime()-new DateTime(1970,1,1)).TotalMilliseconds%> < elapsedMillis)
{
//do stuff
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.