-
PHP: converting string into formatted date
Posted on January 8th, 2009 No comments
While coding I came across the following situation: a date which was showed with the format YYYY-MM-DD, but I wanted its format to be DD-MM-YYYY.Obviously there’s the PHP Date function, you will think, but the point here is that the initial date was a variable as string. Therefore using directly the date function did not work…luckily it is not difficult to find out how to get the desired results.
I simply could not choose it not to be a string, as the variable retrieved the date from a MySQL database where it was stored as a varchar string (no, I did not decide neither program this).
What I did is the following (supposing the original retrieved date as string is “2009-10-03″):
<? $date = "2009-10-03"; // Convert date string into UNIX timestamp $timestamp = strtotime($date); // Convert timestamp into formatted date $date = date("d-m-Y", $timestamp); // Show result echo $date; ?>The resulting date should look like 03-10-2009. Obviously by changing the format parameters of the date function you can shape the result in many other ways. The full list of available format parameters can be found here.
The process consisted basically in transforming a string into a timestamp, because the date function works with the second but not with the first. Simple and useful.
Leave a reply


