Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PHP date into javascript date format

I have a PHP script that outputs an array of data. This is then transformed into JSON using the json_encode() function.

My issue is I have a date within my array and it's not in the correct JavaScript format. How can I convert this within PHP so it is?

$newticket['ThreadID'] =  $addticket;
$newticket['Subject'] =  $subject;
//$newticket['DateCreated'] =  date('d-m-Y G:H');

Instead of the above for the date I need the equivalent of the JavaScript function

new Date()

When I output the above I get the following "Fri Jun 01 2012 11:08:48 GMT+0100 (GMT Daylight Time)" However, If I format my PHP date to be the same, then JavaScript rejects it. Confused...

Can anyone help?

like image 935
LeeTee Avatar asked May 31 '12 15:05

LeeTee


3 Answers

You should probably just use a timestamp

$newticket['DateCreated'] = strtotime('now'); 

Then convert it to a Javascript date

// make sure to convert from unix timestamp var now = new Date(dateFromPHP * 1000); 
like image 160
jeremyharris Avatar answered Oct 04 '22 16:10

jeremyharris


Javascript Date class supports ISO 8601 date format so I would recommend:

<?php 
      date('c', $yourDateTime); 
      // or for objects
      $dateTimeObject->format('c');
?>

documentation says that: format character 'c' is ISO 8601 date (added in PHP 5)
example: 2004-02-12T15:19:21+00:00

for more information: http://php.net/manual/en/function.date.php

like image 42
Javlonbek Avatar answered Oct 04 '22 17:10

Javlonbek


It is pretty simple.

PHP code:

$formatted_date = $newticket['DateCreated'] =  date('Y/m/d H:i:s');

Javascript code:

var javascript_date = new Date("<?php echo $formatted_date; ?>");
like image 38
Rahul Gupta Avatar answered Oct 04 '22 17:10

Rahul Gupta