1

Php has two way to do date manipulation. That is DateTime object and date function. What is the best way to do? What is the way is fastest? Are they have different? I think DateTime wast memory to create a object and have to write more code.

e.g -

  1. get current date

    $do = new DateTime('now');
    print $do->format('Y-m-d H:i:s');
    

or

print date('Y-m-d H:i:s'); 
  1. compair the time

    $datetime1 = new DateTime('2009-10-11');
    $datetime2 = new DateTime('2009-10-13');
    $interval = $datetime1->diff($datetime2);
    echo $interval->format('%R%a days');
    

or

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
MrCode
  • 63,975
  • 10
  • 90
  • 112
Dinuka Thilanga
  • 4,220
  • 10
  • 56
  • 93
  • DateTime object should be used for all new code. It is far easier to use than the old date()/time() functions, which have a **LOT** of implicit gotchas that WILL screw over your code. – Marc B Jun 27 '13 at 15:54
  • Which way is the fastest is a question you can probably answer yourself. Look into http://stackoverflow.com/questions/1200214/how-can-i-measure-the-speed-of-code-written-in-php – Bailey Parker Jun 27 '13 at 15:56
  • 2
    When in doubt, use the object oriented approach. You will seldom have to micro-optimize your code to the point where the overhead will become relevant. – Fusselwurm Jun 27 '13 at 15:56
  • ^ I agree with the above. In my personal opinion, I think it really matters on the situation. Using the `DateTime` class to just get the current date would be overkill when you can just use `date()`. If there are plans to do date calculations, formatting, etc., I'm all for `DateTime`. – Rob W Jun 27 '13 at 16:01

1 Answers1

0

there are lots of advantage to use datetime class instead of date function in latest PHP version and some of them are below.

=> 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 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).

liyakat
  • 11,825
  • 2
  • 40
  • 46