1

This is probably very trivial but I can't for the life of me find any good documentation. I have an AJAX event setup where I need to send a timestamp from the client side to the server. The server script (PHP) will check the timestamp that it has been passed, against a CURRENT_TIMESTAMP in a mysql table and act upon the results.

My problem is that I need to create a timestamp in JavaScript on the client page that will be comparable to the mysql timestamp.

2 Answers 2

1

Alex almost had it

The only thing that is wrong is that JS timestamps are in milliseconds and UNIX timestamps are in seconds. Therefore you need to divide the JS timestamp by 1000.

var unixNow = Math.round( (new Date().getTime()) / 1000);
Sign up to request clarification or add additional context in comments.

1 Comment

Damn, did I mistake multiplication with division? That's what I get for working on a public holiday...
1

How about just sending seconds from Epoch from JavaScript...

var secondsFromEpoch = ~~(+new Date / 1000);

..and then change your query to...

WHERE UNIX_TIMESTAMP(`datetime`) == :secondsFromEpoch_passed_from_JavaScript

?

5 Comments

Some explanation for alex's tricky JS here. + new Date is the same as new Date().getTime() the + converts the date to a number. The ~~ is another way to implement Math.round(), I've heard it's even faster
@JuanMendes Thanks for the explanation. However, + calls the Date's valueOf() which returns a Number. Secondly, ~~, or double invert bits, is functionally the same as Math.floor().
@alex: First: You said the same thing I said??? The + before a date converts it to a number of milliseconds, you just added that it's because it calls valueOf(). Secondly ~~ is not the same as Math.floor either, so we were both wrong. Math.floor(-8.3) == -9 and ~~(-8.3) == -8. Therefore, it's the same as Math.floor for positive numbers and Math.ceil for negative numbers. So I don't think it's a very good idea, since you'd have different behavior for dates before and after 1970.
@JuanMendes I had not noticed the negative number problem before, I'll have to be mindful of that in the future. Also, is exploiting the fact the date works with a negative Number a good way to work with pre 1970 dates? That's a question in itself I guess...
Never had a problem with negative dates. From developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… The JavaScript date is measured in milliseconds since midnight 01 January, 1970 UTC. A day holds 86,400,000 milliseconds. The JavaScript Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.