Datetime Class VS. Native PHP Date-Functions

DateTime class vs. native PHP date-functions

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.

Date changes when using the DateTime class and the modify() method

The method DateTime::modify (add and sub also) is to modify the class (don't to create a new own). As you can see on the manual:

$date = new DateTime('2006-12-12');
$date->modify('+1 day');

echo $date->format('Y-m-d');//2006-12-13

When you assign the returned date with a new variable, you're assigning only a reference. Wich means that both variables are looking to the same object in memory.

$date = new DateTime('2006-12-12');
$nextDay = $date->modify('+1 day');

echo $date->format('Y-m-d');//2006-12-13
echo $nextDay->format('Y-m-d');//2006-12-13

If you want to change a DateTime without modifying the object (creating a new one) use DateTimeImmutable

$date = new DateTimeImmutable('2006-12-12');
$nextDay = $date->modify('+1 day');

echo $date->format('Y-m-d');//2006-12-12
echo $nextDay->format('Y-m-d');//2006-12-13

Another approach is with clone keyword:

$first = clone $last = new \DateTime(date('d-m-Y',time())); //this being todays date 21-03-2017

$first->modify('first day of this month');
var_dump($first);

$last->modify('last day of this month');
var_dump($last);

Code: https://3v4l.org/rO7Zd
Result:

object(DateTime)#2 (3) {
["date"]=>
string(26) "2017-03-01 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
object(DateTime)#1 (3) {
["date"]=>
string(26) "2017-03-31 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}

When do we chose DateTime over Timestamp

As said in a comment I believe this is mostly down to personal preference. In my eyes, the use of a Unix timestamp and "legacy" non-OOP interfaces is not the way to do it going forward in today's world, for instance, we don't (read: shouldn't be) using an INT datatype in our database to store dates in Unix Timestamp format, we should instead be using the database's native type which is usually a DATE or DATETIME type which cooperates with PHP's DateTime object (and other languages') almost natively when it comes to standard conversions.

To elaborate a bit on what I mean by standard conversions: When you use MySQL and pull back a value to PHP you get a ISO-formatted date string, of which the DateTime class parses in it's constructor giving you an immediately usable object. In contrast, to go the Unix timestamp route you would have to use strtotime, then date to get it into whatever format you want natively.

I mentioned before about interop between our PHP systems and .NET systems. Whilst there are no specific issues caused by using a timestamp it's simply not the practical solution, as again, we use a database that returns a DateTime value which can be sent straight down the pipe. If we were to convert this to a unix timestamp for use internally in PHP we'd also have to then convert it back out if we were to send a response, or send a response to the .NET Application (or should I just say API in this case) that is a timestamp, and convert it at the end. By using DateTime across the board, it alleviates the need for any conversions to happen whatsoever and the whole development process is easier.

Finally to add to all of this, as you also mentioned in your post, you get to use shiny items such as DateInterval, easier timezoning, easier manipulation and easier formatting etc when you use DateTime and it's related object-oriented partners in crime. It's just an easier development process in my eyes.

I don't believe as I initially said that there is a "correct" answer to this, just more of a personal preference based on your own coding style, and the comments above reflect mine.

Is the 2 more bytes of DateTime a loss in really simple use of the API (only displaying)

  • I do not believe so in any way. Especially with PHP scripts generally being such short running processes anyway.

Is it the time to give up unix_timestamp?

Yes :)

Wouldn't it be better to store a simple timestamp and then get the good local time?

See comments above on database, it's not "native" to use a Unix Timestamp for this purpose IMO. You can just call ->getTimezone and store this in the database, then use ->setTimezone when you pull it back out again.

Transform DateTime variable into minutes

The strtotime() and date() functions are not recommended anymore. Use the DateTime class.

$datetime = '2012-09-09 01:40';
$d = new DateTime($datetime);
var_dump( $d->format('G') * 60 + $d->format('i') );

Month by week of the year?

print date("m",strtotime("2011-W6-1"));

(noting that in 2011, January has six weeks so week 6 (by some definitions) is in month 1).

what is the most efficient way to get 1 or 2 day before the first day of week number and year in php with native functions

strtotime('2012W01 - 2 days') for Saturday and
strtotime('2012W01 - 1 day') for Sunday since the week call is always going to return you a Monday.

php DateTime with date without hours

set argument for constructor

$d = new \DateTime("midnight");

UPD: if an object already exists with any time

$d->settime(0,0);

result

DateTime Object
(
[date] => 2016-04-20 00:00:00.000000
[timezone_type] => 3
[timezone] => UTC
)

Formatting the Timestamp in UserSpice

you need to format date using strtotime function: (replace $date with your date variable)

$date = '2016-01-01 00:00:00';

echo date('F Y', strtotime($date));

output:

January 2016

Here DateTime class is better option:

$datetime = new DateTime($date);

echo $datetime->format('F Y');

Output:

January 2016

For more detail have look at http://php.net/manual/en/function.date.php and http://php.net/manual/en/class.datetime.php



Related Topics



Leave a reply



Submit