PHP getdate() 与 date()
理论问题。
想象一下情况。我需要获取今天的日期和时间(不是现在,而是今天——一天的开始)。我可以使用以下代码来完成此操作:
$now = time();
$today = date('Y-m-d H:i:s', mktime(0, 0, 0, date("m", $now), date("d", $now), date("Y", $now)));
或这样:
$now = getdate();
$today = date('Y-m-d H:i:s', mktime(0, 0, 0, $now['mon'], $now['mday'], $now['year']));
在我见过的大多数示例中,使用第一种方法。问题很简单:为什么?第一个使用了 3 个函数调用来获取月、日和年。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这两个选项都非常可怕 - 如果您试图以格式化字符串的形式获取午夜的当前日期,则很简单:
或者,如果您想更明确一点,则
无需这样做>mktime 的事情。编写该代码的人不知道自己在做什么和/或者是复制粘贴/货物崇拜开发人员。如果您确实在“大多数示例”中看到了这一点,那么与您一起出去玩的人群深感困扰,您可能应该停止与他们一起出去玩。
mktime
唯一有趣的事情是尝试使用本地时区。如果您的工作对时区敏感,并且您使用的是 PHP 5.3 或更高版本,请考虑使用 DateTime 和 DateTimeZone 代替。 PHP交互提示的演示:(目前UTC为第9,PDT为第8。)
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:
Or, if you want to be slightly more explicit,
No need to do that wacky
mktime
thing. 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 troubled and you should probably stop hanging out with them.The only interesting thing that
mktime
does 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 DateTime and DateTimeZone instead. A demo from the PHP interactive prompt:(At the moment, it is the 9th in UTC, while it's the 8th in PDT.)