geocoder geocoder - 6 months ago 56
JSON Question

Convert a string to date from json file

I want to get data from a json file on order to populate a postgres spatial database.

in the json file, the date data is stored in : "dt_txt": "2016-05-21 03:00:00", and I want to store 2016-05-21 in date.

$json_d=file_get_contents('file.json);
$data=json_decode($json_d,TRUE);
$date=$data['list'][0]['dt_txt'];
$dbconn = new PDO("pgsql:host=localhost; port=5432; dbname=DB", "postgres", "0000");
$insertmbr = $dbconn->prepare("INSERT INTO weather(date) VALUES(?)");
$insertmbr->execute(array($date));


when i run the code this error appears


Fatal error: Call to a member function format() on a non-object

Answer

You need to convert it to a timestamp first

$date = strtotime($data['list'][0]['dt_txt']);

Then you can use the date method to format it as desired:

$date = date('Y-m-d', $date);

You can also extract the time using the same command:

$time = date('H:i:s', $date);

Or, alternatively you could just split the string on the space using explode:

list($date, $time) = explode(' ', $date, 2);

Comments