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)); ?>); 
Ben
  • 4,301
  • 6
  • 37
  • 61
  • 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. – Beenish Khan Apr 19 '12 at 17:04
  • you'll need to put `"` as the timestamp is a string – hjpotter92 Apr 19 '12 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. – Travesty3 Apr 19 '12 at 17:12

3 Answers3

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.

Travesty3
  • 14,351
  • 6
  • 61
  • 98
2

I think that very simple and more universal solution would be

var dateTime = <?php echo date('c', strtotime($yourDateTime)) ?>;
Javlonbek
  • 281
  • 2
  • 7
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

Vipin Jain
  • 1,382
  • 1
  • 10
  • 19