7

How can I pass a datetime/timestamp from PHP to javascript. The following does not appear to work:

startLive = new Date(<?php echo date("U", strtotime($start_date)); ?>); 
3
  • Please provide more information such as Where are you writing this line ? Within a Jvascript script tag or somewhere else, if you can share a little more code, I might be able to guide you better. Commented Apr 19, 2012 at 17:04
  • you'll need to put " as the timestamp is a string Commented Apr 19, 2012 at 17:04
  • @ChasingDeath: Sure, date returns a string in PHP, but specifying the format as "U", really it's an integer value (even though the variable type is string). Javascript still takes it as an integer, so that's not the problem. Really, I think the only problem here is that he needs to multiply it by 1000 to convert it to milliseconds. Commented Apr 19, 2012 at 17:12

3 Answers 3

30

Try this:

startLive = new Date(<?php echo strtotime($start_date)*1000; ?>);

Explanation:

PHP's strtotime function returns a Unix timestamp (seconds since 1-1-1970 at midnight).

Javascript's Date() function can be instantiated by specifying milliseconds since 1-1-1970 at midnight.

So multiply seconds by 1000 and you get milliseconds, which you can use in Javascript.

Sign up to request clarification or add additional context in comments.

Comments

2

I think that very simple and more universal solution would be

var dateTime = <?php echo date('c', strtotime($yourDateTime)) ?>;

Comments

0

You can use this:

startLive = new Date("<?php echo date("F d, Y G:i:s",strtotime($start_date)); ?>");

this will sort your problem

Explanation:

Check Here

Comments

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.