0

I am trying to format a PHP date to be of the following format:

Wednesday 3rd November 2021 at 11:01am

My code is below:
$date = new DateTime($dateOfChange);
$date = $date->format('l jS F Y "at" g:ia');

I have tried:
$date = $date->format('l jS F Y "at" g:ia'); // displays: "am01"
$date = $date->format('l jS F Y at g:ia'); // displays: am01

I can't see a relevant section in the documentation (https://www.php.net/manual/en/datetime.format.php)

1
  • Escaping of literal characters can be done by prefixing them with a backslash. Commented Nov 24, 2021 at 12:36

1 Answer 1

2

This should do the trick...

$date->format('l jS F Y \a\t g:ia');

You need to escape characters that are not intended to be used for date values.

Note that if you're using " instead of ' for your format string you'll need to double escape n, t and r characters as PHP will interpret them as newlines, tabs etc...

For example:

$date->format("l jS F Y \a\\t g:ia");
Sign up to request clarification or add additional context in comments.

3 Comments

Should not need a double backslash before the t, in a text literal delimited with single quotes.
@CBroe I've updated my answer. Hopefully more informative!
@LeviCole Great stuff - thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.