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.
- Would you agree with that ?
- Does it make sense at all to us a DateTime object for simple stuff ?
- Are there any other drawbacks ?
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:
- Converting a date to a localized value
- Calculating the time between two dates
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.
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.
For the record, I did the mistake to use the class DateTime. It was a big mistake. While it has some nice features, but it is not worth the effort. I explain:
Let's say that you have a form (with a date-picker) and you are storing into the database, then you have 3 formats to represent the date.
So, I am dealing with 3 different kinds of representation for the same type of data
Also, let's say that you want to serialize (json, xml or such), it is the serialization:
It is a real pain to try to serialize. My alternative is simple, to store any temporal date as a string and I will convert it to DateTime only if it's needing.