If you using ZF there is a high chance that you also using Zend Date when dealing with date and time.
One day you might need to get the date from a Zend Date object into Mysql format, but you will find out that none of the constants provides this. It’s a decision from developers to don’t mix database stuff with Zend Date.
Fortunately there is an easy way of doing this. If you have date fields on Mysql, you can use:
$date = new Zend_Date();
// Date field
echo $date->get('yyyy-MM-dd');
// Date time field
echo $date->get('yyyy-MM-dd HH:mm:ss');
But hold on, don’t start to write ‘yyyy-MM-dd’ everywhere on your application. If one day you change your database engine, or use a MySQL server with a different locale, you will need a good search and replace software to do it.
Instead of it, you can use a class with constants for the two field types. In this example i called the class Fm_Utils, but you can use the name that fits better on your application:
<?php
class Fm_Utils
{
const DATABASE_DATE = 'yyyy-MM-dd';
const DATABASE_DATETIME = 'yyyy-MM-dd HH:mm:ss';
}
Now you can simple use this to get date in Mysql format:
$date = new Zend_Date(); // Date field echo $date->get(Fm_Utils::DATABASE_DATE); // Date time field echo $date->get(Fm_Utils::DATABASE_DATETIME);
And if one day you need to change your data platform, simply change the constant on this class.
Thanks for this, why does this method work, but:
echo Zend_Date::get(‘YYYY-MM-dd HH:mm:ss’);
Does not?
Hello,
Calling methods with :: is only used for static ones. get() method in Zend_Date is not static, so this won’t work.
neat post… thanks 4 sharing.
@Jay, in case you were looking for something to use with just one line of code, try something like:
$mydate = Zend_Date::now()->get(‘YYYY-MM-dd HH:mm:ss’);
The constants in the class was very useful for me. Thanks!
Thanks man..
Thank you for the clean explanation and code!