Posts tagged ‘zend date’

Get date in Mysql format from Zend Date

25 October, 2010 | | 5 Comments

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.