PHP 日期格式、删除时间等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12447110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:36:00  来源:igfitidea点击:

PHP date format, remove time and more

phpdatedatetimedate-format

提问by itsme

Possible Duplicate:
Convert one date format into another in PHP

可能的重复:
在 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.
  1. 从字符串中删除时间,因此它将变为"2012-09-09".
  2. 使用服务器当前日期/时间/时区计算自该日期以来已经过去了多少年、多少天和多少小时。

Could anyone help me figure this out?

谁能帮我解决这个问题?

回答by Mihai Iorga

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

回答by JvdBerg

$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

您可以使用适合您的间隔。见http://php.net/manual/en/class.dateinterval.php