In my PHP app, I get dates from the MySQL database, when I format them with PHP’s date() command. I want to tidy that up and move it all entirely to the view, rather than the retrieval. But I ran into some problems.
When getting a date from the database, I pass it to the rest of the app after running strtotime() on it, so that the date() functions have something they can work with. Is this a good idea? or am I missing something better and obvious? The dates that I’m dealing with are nearly all in the DATE type, not DATETIME.
So, I get the date, and can use date() to display it on the webpage. But sometimes, I’ll get something from the database solely to insert elsewhere in the database, and having to hunt through the backend to find places that need date() kind of defeats the purpose of separating it out to the view. My retrieval functions helpfully return strtotime($date_from_db), and then I create the new entry into the other table… and all new entries must pass through the validation and preparation functions. And herein lies the problem. I validate and prepare dates by seeing if they strtotime() to something other than 0000-00-00. But I can’t run strtotime() on a timestamp; in the test I ran, if gave me 12/31/1969. So my questions:
- Is it possible somehow to run
strtotime()on a timestamp? - If not, is there an easy way to know if a variable is a timestamp? So I could simply run
date()on it rather than dealing withstrtotime()? Apart from seeing if it comes out to 12/31/1969, because I don’t know if I can trust a failure to be consistent. Unless that’s a valid thing to do anyway? - And am I doing this completely wrong?
As a general approach, I’d be very tempted to :
Store date/time values using MySQL’s datetime type, as this will allow you to meaningfully query the data within MySQL without having resort to either using >= “timestampvalueX”, etc.
Keep all “live” date information using within PHP scripts in timestamp format.
As such, you probably want to aim to store all of the date/time related information in that format as a goal. You can the trivially convert this into a format PHP can use either in the query itself (using UNIX_TIMESTAMP) or by exploding the YYYY-MM-DD HH:MM:SS format and using PHP’s mktime to create a “standard” timestamp. (Although you might want to use checkdate for validation purposes.)
Getting back to your specific questions:
strotime will fail if a timestamp is passed.
As an interim measure you could write a function that checked if the provided value was a 10 digit integer, and presume that it was a native timestamp if it was. (
if(is_int($value) && strlen($value) == 10)...)It’s a bit of a mess by the sounds of things, so as a reasonably short term goal you should probably try and standardise usage both in MySQL and PHP.