Skip to content
Advertisement

date_i18n function shows today’s date instead of provided date

I’m triying to display the a span of dates from starting date to ending date in WordPress in a custom snippet to list events on our website. There are two custom fields relevant for this problem:

  • event_date: shows the starting date of the event (using date picker)
  • event_date_end: shows the ending date of the event (using date picker, only used when the event is more than one day)

I’m using the code below, It looks right to me but for some reason the second date is set to today’s date instead of the date in the event_date_end field. If I display only event_date_end (echo get_field(‘event_date_end’) for instance) the right date shows up but when trying to change how it is displayed for some reason the date changes. Any idea what may cause this? The whole thing is part of a longer snippet so perhaps the error is outside of this scope but I have a feeling I’m not using i18n correctly.

$eventduration = date_i18n("d", strtotime(get_field('event_date')))."
".date_i18n("M", strtotime(get_field('event_date')))." -
".date_i18n("d", strtotime(get_field('event_date_end')))."
".date_i18n("M", strtotime(get_field('event_date_end')))."; 
echo $eventduration;

#Should display something like "25 Aug - 28 Aug" but instead shows "25 Aug - 18 Aug"

Advertisement

Answer

If you pass a date with / as a seperator strtotime() it will assume the American date format.

Your date from the date picker is in a logical format. So you will have to change the / to a - and then strtotime() will work correctly for this format

$ede = str_replace('/', '-', get_field('event_date_end'));

$eventduration = date_i18n("d M", strtotime(get_field('event_date')))
                 ." - ".
                 date_i18n("d M", strtotime($ede)); 
echo $eventduration;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement