PHP date format, remove time and more [duplicate]

谁说我不能喝 提交于 2019-12-04 16:40:55

问题


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?


回答1:


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)
} */



回答2:


$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



来源:https://stackoverflow.com/questions/12447110/php-date-format-remove-time-and-more

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!