Michelangelo
Michelangelo

Reputation: 1397

Strange error in the Zend_Date localization

I have two problems in my little script. I am trying to create an application that use Zend Framework 1.12.1, Doctrine, Zend_locale, Zend_Currency and Zend_Date.

Dates:

The database needs a date in this format Y-m-d H:i:s but each user set their locale preferences in the custom control panel. So when I get a date from the database I have to convert it in the locale choosen.

This is my code:

<?php

     $dboutdata = "4/3/13 12:00 AM"; // 4 March 2013 12:00 AM

     $date = new Zend_Date($dboutdata, null, "en_US");
     echo $date . "<br/>";

     $date = new Zend_Date($dboutdata, null, "it_IT");
     echo $date . "<br/>";

?>

this is the result:

Apr 3, 13 12:00:00 AM
04/mar/13 12.00.00

As you can see the result is wrong. Zend_Date confuses the month with the day. How have I to solve this problem?

updates:

/**
 * Convert a date from yyyy/mm/dd formatted by the locale setting
 *
 * @param date $dbindata
 * @return date formatted by the locale setting
 */
static public function formatDateOut($dbindata) {
    if (empty ( $dbindata ))
        return false;

    $locale = Zend_Registry::get('Zend_Locale');
    $date = new Zend_Date($dbindata, "yyyy-MM-dd HH:mm:ss", $locale);

    return $date->toString(Zend_Date::DATETIME_SHORT, $locale);
}

/**
 * Convert a date from Zend Locale selected to yyyy/mm/dd H:i:s
 *
 * @param string $dboutdata
 * @return string Y-m-d H:i:s
 */
static public function formatDateIn($dboutdata) {
    if (empty ( $dboutdata ))
        return null;

    $InDb = null;

    $locale = Zend_Registry::get('Zend_Locale');
    $date = new Zend_Date($dboutdata);

    return $date->toString('yyyy-MM-dd HH:mm:ss');
}

Furthermore, If I need to save this date how can I normalize it in order to save it in the database?

Best Regards

Upvotes: 1

Views: 900

Answers (1)

Tim Fountain
Tim Fountain

Reputation: 33148

By passing the locale into the Zend_Date constructor, you're telling it what format the date is in. The US date format has the month first, where as the European date format has the day, so that's why you get different results.

You probably just want to set the locale when outputting the date, e.g.:

$dboutdata = "4/3/13 12:00 AM";
$date = new Zend_Date($dboutdata, null, "en_US");

echo $date->toString(null, 'en_US') . '<br>'; // outputs Apr 3, 13 12:00:00 AM
echo $date->toString(null, 'it_IT') . '<br>'; // outputs 03/apr/13 00.00.00

Upvotes: 1

Related Questions