DateTime类与本机PHP日期函数 [英] DateTime class vs. native PHP date-functions

查看:71
本文介绍了DateTime类与本机PHP日期函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DateTime类肯定具有一些方便的方法,并且似乎总体上优于本机PHP日期函数(例如strtotimemktimestrftime(以及更多)).但是,有什么缺点或原因我不应该使用它吗?

The DateTime class sure has some handy methods and seems overall superior to the native PHP date functions like strtotime, mktime and strftime (and more). But is there any drawback or a reason why I shouldn't use it ?

我能想到的唯一原因是,创建一个类的整个实例可能比仅使用一个函数要昂贵得多.

The only reason I can think of is that it might be more expensive to create a whole instance of a class than just using a function.

  • 您同意吗?
  • 将DateTime对象用于简单的东西完全有意义吗?
  • 还有其他缺点吗?

一直在这两个选项之间切换似乎有些混乱,所以我想弄清楚我应该做的事情.

It seems a bit confusing to switch between those two options all the time, so I'd like to have clearance what I should prefer doing.

我做出决定的两个例子是:

Two examples for my decision would be:

  • 将日期转换为本地化值
  • 计算两个日期之间的时间

推荐答案

如果您担心创建类实例非常昂贵,并且会阻碍性能,那么恐怕您会选择错误的树.人们永远不应该考虑在合理的情况下是否使用经过验证的OO方法.如果为了执行某些日期计算而使用DateTime类有意义,则使用它.除非您进行疯狂的操作(例如创建100万个DateTime对象),否则在您的应用程序感觉不到这一点并不昂贵.

If your worry is that creating a class instance is expensive and that it'll hinder performance, then I'm afraid you're barking at the wrong tree. One should never consider whether to use proven OO approach where it makes sense. If it makes sense to use DateTime class in order to perform certain date calculations, then use it. It's not expensive to the point where your app will feel it, unless you do something crazy such as creating 1 million DateTime objects.

DateTime之所以如此出色,是因为它在创建对象时指定了时区,从而减轻了夏令时的烦恼.获取日期之间的差异或获取不同对象之间的间隔也很容易.基本上可以减少烦恼和所需的编码(但是我承认有时是错误的,希望可以在5.4版本的PHP中得到解决).

Reason why DateTime is great is because it alleviates the worry of daylight savings by specifying the time zone when creating the object. It's also easy to obtain differences between dates or obtain intervals between different objects. It basically cuts down the amount of worry and coding required (but I will admit it is wrong sometimes, hopefully it'll get addressed in 5.4 release of PHP).

底线-我会一直使用它.

Bottom line - I'd always use it.

这篇关于DateTime类与本机PHP日期函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆