I'm building a website with php and i'm using the DATE-type in my MYSQL table to store dates. The problem that i have is that this stores the dates by default in the format YYYY-MM-DD. But i need this format DD-MM-YYYY to appear on my PHP page with the possibility of calculating the amount of days between 2 different dates. How can this be achieved?
Asked
Active
Viewed 349 times
0
-
Where do you want to make the calculations? In the php or in the query? – lvil May 20 '12 at 14:16
-
I want to make those calculations in php, when the page is requested. – the_boy_za May 20 '12 at 14:31
3 Answers
0
You can use strtotime to convert a string representation of the date to an actual date object in php, then use the date function to spit out the date as any string format you wish. Also, you can be strtotime
to perform date calculations. Additional information can be found at this blog post.
$phpDate = strtotime($stringDateFromDb);
date('d-m-y', $dateFromDb);
strtotime('-3 days', strtotime($stringDateFromDb));

saluce
- 13,035
- 3
- 50
- 67
-
a date string from the db will not work. You'll just get Jan 1/1970 since the string will evaluate to time-value `0`. – Marc B May 20 '12 at 14:06
-
@MarcB Then just use strtotime to convert the string to a date (as shown in edited answer) – saluce May 20 '12 at 14:12
0
That's a display problem. Use mysql's date_format()
function to convert to whatever your display requirements are, e.g.
SELECT date_format(datefield, '%d-%m-%Y'), ...

Marc B
- 356,200
- 43
- 426
- 500
-
When i query this in phpmyadmin it works fine. In php i dont get anything returned. ` $query2 = "SELECT date_format(startdate,'%d-%m-%Y'), date_format(enddate,'%d-%m-%Y') FROM articles WHERE pkArticle='$articleID'"; $result2 = mysql_query($query2) while($datums = mysql_fetch_array($result2)){ $startdatum = $datums['startdate']; $einddatum = $datums['einddate']; }` – the_boy_za May 20 '12 at 15:45
0
Here is an example for a way to do it:
$date_str = '2012-05-20'; //you get it from db
$date_now = strtotime($date_str); //convert it to unix timestamp
$yesterday=$date_now-24*60*60; //make calculations
echo 'yesterday was: '. date('d-m-Y',$yesterday); //date() returns the date in format you need
Further example here: How to calculate the difference between two dates using PHP?
-
it's easier and more intuitive to use `strtotime` -- `$yesterday=strtotime('-1 day',$date_now);` – saluce May 20 '12 at 22:55
-