How to deal with DATE-type in MYSQL & PHP?

759

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?

45

Answer

Solution:

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

Answer

Solution:

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?

People are also looking for solutions to the problem: session - Bypassing Captcha with curl in PHP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.