Create a constant date format in PHP
I was using CI as my framework. How can I set a CONSTANT date format so that I don't need to change and search for date("y-m-d")
in all file开发者_如何学C?
I haven't tried exactly what you're asking for, but somewhere you should be able to use the define
function to define a constant string matching your format, which you can then reference throughout your app.
Example:
define( 'MY_DATE_FORMAT', "y-m-d" );
$date = date( MY_DATE_FORMAT );
Where you put this in CodeIgniter is a whole other problem. I'll look through the docs and see what I can find.
HTH.
EDIT: Found this forum topic on the CI site: http://codeigniter.com/forums/viewthread/185794/ It should get you started on what you need to do.
Put this is a common header file:
define('my_date_format', 'y-m-d');
To use the constant:
// remember to include the header file first
date(my_date_format);
To format 2010-11-10 10:12:11
to date(m.d.y)
:
$myDate = new DateTime('2010-11-10 10:12:11');
$myDate->format('m.d.y');
I think when you say "constant" date format you mean you want the same output each time, but you don't literally need a constant in the PHP sense. Just write your own function (or in Codeigniter terms, "helper"):
// Apply your default format to $format
function display_date($timestamp = NULL, $format = 'y-m-d')
{
// Possibly do some stuff here, like strtotime() conversion
if (is_string($timestamp)) $timestamp = strtotime($timestamp);
// Adjust the arguments and do whatever you want!
// Use the current time as the default
if ($timestamp === NULL) $timestamp = time();
return date($format, $timestamp);
}
Example usage:
echo display_date(); // Current time
echo display_date($user->last_login); // Formatted unix time
echo display_date('Next Monday'); // Accept strings
Writing your own function allow much more flexibility in the future.
精彩评论