Asked  7 Months ago    Answers:  5   Viewed   44 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

75

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);
Wednesday, March 31, 2021
 
employeegts
answered 7 Months ago
68

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

Wednesday, March 31, 2021
 
jwegner
answered 7 Months ago
76

Your current method is correct, dividing by 1000 is necessary because your JavaScript returns the timestamp in milliseconds, and datetime.datetime.fromtimestamp() expects a timestamp in seconds.

To preserve the millisecond accuracy you can divide by 1000.0, so you are using float division instead of integer division:

>>> dt = datetime.datetime.fromtimestamp(jsts/1000.0)
>>> dt
datetime.datetime(2012, 4, 23, 11, 30, 4, 950000)
Wednesday, June 30, 2021
 
SilverHorn
answered 4 Months ago
45

You need some JS that parse the String and return the year, month, day, minute,hour, second in strings:

var hour = ds.split(":")[0],
    minute = ds.split(":")[1],
    last_part = ds.split(":")[2],
    second = second_part.split(" ")[0],
    last_part2 = second_part.split(" ")[1],
    day = last_part2.split("/")[0],
    month =  last_part2.split("/")[1],
    year =  last_part2.split("/")[2];

and then instantiate the Date constructor:

var d = new Date ( year, month, day, hour, minute, second );
Thursday, August 12, 2021
 
Travis
answered 3 Months ago
37

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, August 19, 2021
 
smiggle
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :