Escape characters in the PHP date functionPosted in PHP -
It's funny when you've been programming in a language for a long time and fall into odd assumptions about particular functions. For some reason I appear to have assumed there was no way to escape characters in PHP's date function. Then yesterday I saw some sample code where a character was escaped and double checked in the manual. Sure enough, you can escape characters and it's obvious. I just thought I'd share it here in case you're making the same mistake I was.
Escape characters in date with \
As an example, there are some date formats that require a string constant T between the date and time parts of the timestamp, but not the timezone offset as well (the 'c' format character will do the T but also include the offset at the end).
This is what I'd been doing in the past:
// don't do this yourself, use the second example below $datetime = date('Y-m-d') . 'T' . date('H:i:s');
By escaping the T with a \ you can do it with one call to the date function, which is much more sensible and I don't know why I never checked the online documentation in the past to see if it could be done more concisely:
$datetime = date('Y-m-d\TH:i:s');
A note about escaping characters
Some letters do not have an associated format in the PHP date function; for example 'x' passed in the format string will currently return a literal 'x'. However, there's no guarantee that 'x' will never have a format associated with it and at some stage in the future a format may be assigned to it.
So whenever you need a literal character to be represented in a date formatted string, always escape it with \.
There are more examples in the manual page - scroll down to the examples on that page where you can find a whole bunch of escaping examples.