0

I need to convert mysql datetime to php Y-m-d. Essentially I just need to drop the hh:mm:ss from the datetime. How can I do this?

Furthermore, once I have the PHP dates in the format Y-m-d how can I do a comparison of two dates to tell which is higher? For example if I have 12-31-13 and 1-1-14 can I just do if (12-31-13 < 1-1-14)?

John Conde
  • 217,595
  • 99
  • 455
  • 496
Aaron Hiniker
  • 3,923
  • 6
  • 21
  • 14

3 Answers3

3
$formattedDate = date("Y-m-d", strtotime($mysqlDate));

  if (strtotime($somedate) >strtotime($someotherdate)){
 // do stuff here
 }

strtotime standardizes most dates and times into the number of seconds since jan1 1970.

Altimus Prime
  • 2,207
  • 2
  • 27
  • 46
2

I need to convert mysql datetime to php Y-m-d. Essentially I just need to drop the hh:mm:ss from the datetime. How can I do this?

Use MySQL's DATE() function

Furthermore, once I have the PHP dates in the format Y-m-d how can I do a comparison of two dates to tell which is higher? For example if I have 12-31-13 and 1-1-14 can I just do if (12-31-13 < 1-1-14)?

You can compare DateTime objects. (Notice the formats of the dates)

$date1 = new DateTime('13-12-31');
$date2 = new DateTime('14-01-01');
if ($date1  < $date2)
{
    // do stuff
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • No. `date()` expects a timestamp as the second parameter and the order of the date parts are incorrect. – John Conde Aug 14 '13 at 19:39
  • So this: $timestartDate = date("Y-m-d", strtotime($timestart)); Can I then pass $timestartDate into new DateTime like $date = new DateTime($timestartDate); ? – Aaron Hiniker Aug 14 '13 at 19:41
  • 1
    I am not sure your original date formats (mm-dd-yy) will work with strtotime but it might. Give it a try and see. You can also use `$date1 = DateTime::createFromFormat('m-d-y','12-31-13')` which is probably better. – John Conde Aug 14 '13 at 19:43
  • what's the benefit of using this more complex method vs. strtotime? – LobsterMan Apr 09 '15 at 09:14
  • DateTime is more flexible and powerful. And more readable, too. – John Conde Apr 09 '15 at 11:46
1

for comparing date use strtotime, and date u can find plenty of examples.

$orig = "2000-01-01";
$new = date("d-m-Y", strtotime($orig));

after thad you can compare dates like $orig > $new

JTC
  • 3,344
  • 3
  • 28
  • 46