Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

strtotime - DateTime class vs. native PHP date-functions

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...