php getdate() 与 date()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5602858/
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 21:57:03  来源:igfitidea点击:

php getdate() vs date()

phpdategetdate

提问by kpower

Theoretical question.

理论问题。

Imagine the situation. I need to get today date and time (not now, but today - the start of the day). I can do it with either this code:

想象一下这种情况。我需要获得今天的日期和时间(不是现在,而是今天 - 一天的开始)。我可以使用以下代码来做到这一点:

$now = time();
$today = date('Y-m-d H:i:s', mktime(0, 0, 0, date("m", $now), date("d", $now), date("Y", $now)));

or this:

或这个:

$now = getdate();
$today = date('Y-m-d H:i:s', mktime(0, 0, 0, $now['mon'], $now['mday'], $now['year']));

In most examples I've seen, the first way is used. The question is simple: why? The first one uses 3 function calls more to get month, day and year.

在我见过的大多数例子中,使用了第一种方式。问题很简单:为什么?第一个使用 3 个函数调用来获取月、日和年。

回答by Charles

Both of those options are pretty horrible -- if you're trying to get the current date at midnight as a formatted string, it's as simple as:

这两个选项都非常糟糕——如果你想在午夜获取当前日期作为格式化字符串,那么简单如下:

date('Y-m-d') . ' 00:00:00';

Or, if you want to be slightly more explicit,

或者,如果你想更明确一点,

date('Y-m-d H:i:s', strtotime('today midnight'));

No need to do that wacky mktimething. Whoever wrote that code does not know what they are doing and/or is a copy-paste/cargo-cult developer. If you really see that in "most examples," then the crowd you're hanging out with is deeply troubledand you should probably stop hanging out with them.

没必要做那种古怪的mktime事情。编写该代码的人不知道他们在做什么和/或是复制粘贴/货物崇拜的开发人员。如果您真的在“大多数示例”中看到了这一点,那么与您一起出去玩的人群会非常困扰,您可能应该停止与他们一起出去玩。

The only interestingthing that mktimedoes is attempt to work with the local timezone. If your work is timezone sensitive, and you're working with PHP 5.3 or better, consider working with DateTimeand DateTimeZoneinstead. A demo from the PHP interactive prompt:

唯一有趣的事情mktime是尝试使用本地时区。如果您的工作对时区敏感,并且您使用的是 PHP 5.3 或更高版本,请考虑改用DateTimeDateTimeZone。来自 PHP 交互式提示的演示:

php > $utc = new DateTimeZone('UTC');
php > $pdt = new DateTimeZone('America/Los_Angeles');
php > $midnight_utc = new DateTime('today midnight', $utc);
php > $midnight_utc->setTimeZone($pdt);
php > echo $midnight_utc->format('Y-m-d H:i:s');
2011-04-08 17:00:00

(At the moment, it is the 9th in UTC, while it's the 8th in PDT.)

(目前,它在 UTC 中是第 9 位,而在 PDT 中是第 8 位。)