PHP / Zend custom date input formats
I'm creating a library component for other developers on my team using PHP and Zend. This component needs to be able to take as input a date (string) and another string telling it the format开发者_Python百科 of that date. Looking through the Zend documentation and examples, I thought I found the solution -
$dateObject = Zend_Date('13.04.2006', array('date_format' => 'dd.MM.yyyy'));
this line, however, throws an error - call to undefined function.
So instead I tried this -
$dt = Zend_Locale_Format::getDate('13.04.2006', array('date_format' => 'dd.MM.yyyy'));
This gets the job done, but throws an error if a date that is entered isn't valid. The docs make it look like you can use the isDate() function to check validity -
Zend_Date::isDate('13.04.2006', array('date_format' => 'dd.MM.yyyy'))
but this line always returns false.
So my questions -
Am I going about this the right way? If not, is there a better way to handle this via Zend or straight PHP?
If I do use Zend_Locale_Format::getDate(), do I need to worry about a locale being set elsewhere and changing the results of the call?
I'm locked into PHP 5.2.6 on windows, btw... so 5.3+ functions & strptime() are out.
You might want to try using the Zend_Date constants instead of strings. The reason I say this is looks like there's some inconsistency in the docs:
MM Month, two digit Zend_Date::MONTH 02 MMMM Month, localized, complete Zend_Date::MONTH_NAME February
and then later on:
So, if you are using 'dd.MM.yyyy' you will get '31.December.2007' but if you use 'dd.MM.YYYY' you will get '31.December.2008'
Shows MM showing a string? So your date would not validate given that format. Have you tried isDate without a format?
I've got around this issue by doing this:
try
{
$myDate = new Zend_Date($date, $format, $locale);
}
catch (Zend_Date_Exception $e)
{
$myDate = new Zend_Date::now();
}
$dateObject = Zend_Date('13.04.2006', array('date_format' => 'dd.MM.yyyy'));
throws an error "undefined function" because it is no function. accordingly to the manual Zend_Date is an Object with a constructor and the format string is not given in an array. you have to write it like this
$dateObject = new Zend_Date('13.04.2006', 'dd.MM.yyyy');
and everything is cool.
ciao ulf
精彩评论