As I spend most of my time with php and mysql or pgsql, I will use DateTime as a generic word for the date API. In php there is no "Date", "Time", "DateTime" and "DateTimeOffset"
As I develop web application more and more elaborate, I use DateTime most of time, but sometimes I wonder if it is really what I want.
for example it happens that I just want to display the today's date (for example when I want to store a forum or blog post), there is no calculation, no filter to provide, no iteration to happen... So why do I use \DateTime
over the date()
function?
I saw this topic that provides some simple description of the pros of each technologies.
But it does not really answer to the question. Is it really a loss to throw up 2 more bytes in a DateTime object in PHP and other 2 bytes in my database as it allows me to use the DATE_INTERVAL
API (in php it is DateInterval
) and the IntlDateFormatter.
Moreover, this post says that unix_timestamp is reserved from 1970. But it is not logical and some tests prove it :
echo date('d/m/Y',time(-1));
echoes '31/12/1969' ! And it is logical. A 32 bits unsigned int goes from 0 to 4 294 967 295
and there are only almost 2 billions of seconds in 68 years, so the int is signed and "negative timestamp" must exist !
Another think that is really important to me, and that makes me chose DateTime every time is that I want to deal with dates, not with integers. DateTime is a date, timestamp is not ! The only sense that I found to timestamp was the time I wanted to time-mark a filename because in that cas timestamp is timestamp...
However, ther is still a problem : timezone handling. As MySQL and others does not handle timezone when storing dates as DateTime, for now, I use TimeZone integration as the escape part of "filter in escape out"
$toStoreDate = new \DateTime($_POST['date'],new DateTimeZone('UTC'));
$dao->exec('INSERT INTO mytable(mydate) VALUES (\''.$toStoreDate->format('Y-m-d h:i:s').'\')');
$toDisplayDate =new \DateTime( $dao->query('SELECT mydate FROM mytable')
->fetch(DAO::FETCH_ASSOC)['mydate']);
$toDisplayDate->setTimeZone(new DateTimeZone('myLocal'));
Is it the right way? Wouldn't it be better to store a simple timestamp and then get the good local time?
So, here is a summarise of the question :
- Is the 2 more bytes of DateTime a loss in really simple use of the API (only displaying)
- Is it the time to give up unix_timestamp?
- Wouldn't it be better to store a simple timestamp and then get the good local time?