DateTime class vs. native PHP date-functions

Anonymous picture Anonymous · Dec 22, 2011 · Viewed 20.6k times · Source

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 use 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

Answer

N.B. picture N.B. · Dec 22, 2011

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.