Embed literal text in PHP date format strings
Posted April 29th, 2010 in PHP
The tip offered in this post is actually documented in date page of the PHP manual but it's one of those things I wasn't aware of until seeing it in an example somewhere else just before posting this so I thought I would share it here. It's how to embed some literal text in the format string for PHP's date function.
What I've done in the past - calling date() twice
In the past if I've needed to have some date formatting, followed by some literal text and then more date formatting I've tended to do something like this, which is inefficient:
$foo = date('Y-m-d') . ' FOO ' . date('H-m-s');
Call date once and escape each literal character
To embed the literal text in the format string simply escape each literal character with a slash. Using the above example again, do this:
$foo = date('Y-m-d \F\O\O H-m-s');
Now there's only one call to the date() function.
And here's the situation where I used it this morning, setting the expires header for a webpage and being able to put the "GMT" part into the format string instead of concatenating it to the end:
header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time()+600 ), true);
Related posts:
- PHP's getdate() function (Monday, April 20th 2009)
- PHP Date Constants (Saturday, August 16th 2008)
- Using strtotime with PHP (Friday, December 21st 2007)
- Formatting Dates with PHP (Thursday, December 20th 2007)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

