Viewed   208 times

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?

 Answers

5

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);
Sunday, December 4, 2022
 
4

You could pass the date / time as a UNIX timestamp which is an integer, a natively supported data type in JSON. DateTime in PHP has a "getTimestamp()" function which will give you that value.

Friday, September 2, 2022
 
5

You need date with strtotime :

<?php
$a = "2016-03-01T03:00:00Z";
echo date("d/m/Y H:i A",strtotime($a));

?>

Demo : http://codepad.org/O73INg7p

Thursday, September 15, 2022
 
mysza
 
4

The PHP code in Luna's answer with echo date isn't exactly like JavaScript code. This will mimic the JavaScript code exactly:

echo date('D M d Y H:i:s O');
Thursday, October 20, 2022
 
skomski
 
5

This should work in Java

Date date = new Date(Long.parseLong(jsonDate.replaceAll(".*?(\d+).*", "$1")));

the problem with your example is that it's only good for javascript

Thursday, November 10, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :