2

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.

blackorchid
  • 377
  • 1
  • 15
  • 2
    I found a calculation by Nick Gotch in [this](http://stackoverflow.com/questions/17950075/convert-c-sharp-datetime-to-javascript-date) SO question. Is that a solution for you? – Jeroen Heier Jul 20 '16 at 18:02
  • @JeroenHeier I think so, basically. But I dislike using numbers without explanation, so I'm going to post a workaround I found slightly more transparent. Thanks for the tip! :) – blackorchid Jul 20 '16 at 18:21
  • 1
    I think [this](http://stackoverflow.com/questions/7966559/how-to-convert-javascript-date-object-to-ticks) question and [this](http://stackoverflow.com/questions/2404247/datetime-to-javascript-date) question have better explanations. – Jasen Jul 20 '16 at 18:28

1 Answers1

3

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>    
blackorchid
  • 377
  • 1
  • 15