I am writing a function in WordPress to add data from an XML file to a MySQL database.
The problems happened after I got a date value from the XML. It’s a string type and I format it to a datetime using this code:
$mysqlDay = date('d/m/Y',strtotime($day));
$day
is a date value retrieved from the XML: “25/01/2013” (d/m/Y). And the value of $mysqlDay
is “01/01/1970” (d/m/Y). Why does the variable $mysqlDay
have value of the beginning day instead the $day
? What should I do if I want to format it from string to date?
In a similar problem to the one above, if I want to convert a string formatted like “18:00” (H:M) to time, what should I do?
I used this code in WordPress to add these values to the database:
$wpdb->insert('wp_lps',
array('date'=>$mysqlDay,
'start'=> $mysqlStartTime,
'end'=> $mysqlEndTime),
array('D/M/Y',
'H:M',
'H:M')
);
Is this right? wp_lps
is the table I created, $mysqlStartTime
and $mysqlEndTime
need to be formatted as H:M.
You can use DateTime instead:
It is more elegant, and object oriented.
In my other answer, I answered the question you actually asked. However, it turns out (after much discussion in comments), that this was the wrong question.
Here’s the situation: you have some XML which contains a date in d/m/Y format. You can fetch that with SimpleXML. Now you have a SimpleXML object. Now you want to get that into the database.
Convert the object to a string:
Convert the date into a format that MySQL recognises as a date.
Insert the date into the database using the
$wpdb
library.Your problem was in a couple of places:
strtotime()
didn’t recognise, for reasons laid out in my other answer.$wpdb
), but it’s still strings under the hood.date()
and/orstrtotime()
returned date objects. They don’t. Thedate()
function returns a string. Thestrtotime()
function returns an integer (which is a UNIX timestamp).strtotime()
function assumes that if a string has slashes in it, it’s an American-style date.Says the documentation.
So you want to convert those slashes to hyphens before calling
strtotime()
.