Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Datetime/Timestamp from PHP to Javascript by echo

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)); ?>); 
like image 434
Ben Avatar asked Apr 19 '12 17:04

Ben


People also ask

How to use PHP date function in JavaScript?

php', function(data) { today = new Date(data); closing = new Date(data); });

How to convert dateTime to timestamp in PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

Why use strtotime?

The strtotime() function is a built-in function in PHP which is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in English date-time description.

What is gmdate in PHP?

The gmdate() is an inbuilt function in PHP which is used to format a GMT/UTC date and time and return the formatted date strings. It is similar to the date() function but it returns the time in Greenwich Mean Time (GMT). Syntax: string gmdate ( $format, $timestamp )


2 Answers

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.

like image 79
Travesty3 Avatar answered Oct 26 '22 07:10

Travesty3


I think that very simple and more universal solution would be

var dateTime = <?php echo date('c', strtotime($yourDateTime)) ?>;
like image 39
Javlonbek Avatar answered Oct 26 '22 08:10

Javlonbek