26

Possible Duplicate:
Convert one date format into another in PHP

Starting from:

$date = '2012-09-09 03:09:00'

I would like to do two things.

  1. Remove the time from the string, so it will become "2012-09-09".
  2. Calculate how many years, days, and hours have passed since this date using the server current date/time/timezone.

Could anyone help me figure this out?

Community
  • 1
  • 1
itsme
  • 48,972
  • 96
  • 224
  • 345
  • Your second question is a duplicate of [How to calculate the difference between two dates using PHP?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – Justin Jun 26 '13 at 09:50

2 Answers2

52

Use DateTime:

$date = '2012-09-09 03:09:00';

$createDate = new DateTime($date);

$strip = $createDate->format('Y-m-d');
var_dump($strip); // string(10) "2012-09-09"

$now = new DateTime();
$difference = $now->diff($createDate, true);
var_dump($difference);

/* object(DateInterval)#3 (8) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(7)
  ["h"]=>
  int(13)
  ["i"]=>
  int(4)
  ["s"]=>
  int(38)
  ["invert"]=>
  int(0)
  ["days"]=>
  int(7)
} */
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
26
$date = '2012-09-09 03:09:00';
$dt = new DateTime($date);

echo $dt->format('Y-m-d');

$interval = $dt->diff(new DateTime());

You can use the interval as it suits you. See http://php.net/manual/en/class.dateinterval.php

JvdBerg
  • 21,777
  • 8
  • 38
  • 55