Making a legible date string from two dates in PHP

When you develop website after website, certain functions come along which save time for the programmer and which provide the website visitor with a professional result. The visitor probably won’t even notice the little nicety, but it’s a nice addition to the browsing experience.

This nicety dates back to the early 2000s, when I worked on an event calendar for the local newspaper. The task is to provide the user with a legible and easily-understandable date explanation, when a start date and optional end date are available.

The premise – and indeed the code – is pretty simple. If only the start date is defined for an event, then only this will be output. If the start and end date fall on the same day, or within the same month, or within the same year, then an appropriately-crafted message will be displayed.

These are the options:

  • On 25th September 2019
  • From 25th to 30th September 2019
  • From 25th September to 10th October 2019
  • From 25th September 2019 to 3rd January 2020

The code is pretty simple. I ensure that the script is efficient by only defining variables when they are needed, and I try to get the simplest cases out of the way first.

(Note that this code outputs date strings in the German format and uses WordPress’ date_i18n function. You can easily change it for your own needs.)

Leave a Reply

Your email address will not be published. Required fields are marked *

For security, use of Google’s reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

I agree to these terms.

This site uses Akismet to reduce spam. Learn how your comment data is processed.