0

I use a timestamp as part of my application, the problem being however that timestamps created in Javascript and SQL Server at the same time show different values. They run on the same computer, so the system clock isn't an issue.

Javascript:

var now = new Date();

console.log( new Date(now.getUTCFullYear(),
        now.getUTCMonth(),
        now.getUTCDate(),
        now.getUTCHours(),
        now.getUTCMinutes(),
        now.getUTCSeconds()).valueOf() /1000);​

SQL Server 2012:

SELECT datediff(second,'1970-01-01 00:00:00.000',getutcdate())

Could it be that the first part of the datediff argument, isn't interpreting 01/01/1970 in UTC?

To test, I executed the javascript in jsfiddle, and rand the SQL in management studio, within 1-2 seconds of each other.

Results: Javascript: 1339348299 SQL Server: 1339384301

So there's a difference of 36002 seconds, or 10 hours, which is my timezone offset.

4
  • How large is the difference between the two?
    – Eric J.
    Commented Jun 11, 2012 at 1:17
  • How are you running these "at the same time" ? in parallel? or does some time elapse between running them? Commented Jun 11, 2012 at 1:42
  • Updated the question with answers to the above q's
    – BlinkyBill
    Commented Jun 11, 2012 at 3:17
  • Yes, the string is being interpreted as local time. I don't know how to to get SQL Server to treat it as UTC, however. Either adding a time zone to the string or setting some locale parameter, most likely.
    – Mark Reed
    Commented Jun 11, 2012 at 3:23

2 Answers 2

1

OK, here are the two methods to get timestamps that will compare...

Javascript

return Math.round(new Date().getTime()/1000.0);

SQL Server

SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())
0

Based on what you're showing, I'd say that one of the two systems has its timezone set incorrectly. You can check this by using the corresponding getdate() (instead of getUTCdate()) functions in each of SQL and javascript and comparing. My guess would be that one of them will return the same as the getUTCdate, suggesting that that one is the one to fix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.