geocoder geocoder - 2 years ago 224
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.

$dbconn = new PDO("pgsql:host=localhost; port=5432; dbname=DB", "postgres", "0000");
$insertmbr = $dbconn->prepare("INSERT INTO weather(date) VALUES(?)");

when i run the code this error appears

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

Answer Source

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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download