1

I have made a custom theme and used CPT UI to create Event Post Type and ACF to create Event Date Field. I am using following code to display Remaining Event Days in frontend:

$event_date = strtotime(get_field('event_date', false, false));
$curr_date = time();
$rem_days = $event_date - $curr_date;
if ($rem_days <= 0) {
    $event_msg = '<strong>Event Expired</strong>';
} else {
    $event_msg = '<strong>' . date('d', $rem_days) . '</strong> Days Remaining';
}

The problem is events in this month are having right remaining days but events with next months are displaying less remaining days.

I don't know what I am missing out. Can you guys please help me?

You can see in screenshot Event with Oct 12 is displaying 23 days remaining, which is right. But event with Nov 3 is displaying just 14 days. enter image description here

1 Answer 1

2

What you did wrong here is the part date('d', $rem_days). The function date() should be used to convert timestamp to a formatted date, not to converting a time difference in timestamp to time difference in days.

You can fix this by replacing date('d', $rem_days) with floor($rem_days/86400).

The complete code should be:

$event_date = strtotime( get_field( 'event_date', false, false ) );
$curr_date  = time();
$rem_days   = $event_date - $curr_date;
if ( $rem_days <= 0 ) {
    $event_msg = '<strong>Event Expired</strong>';
} else {
    $event_msg = '<strong>' . floor( $rem_days / 86400 ) . '</strong> Days Remaining';
}
New contributor
Anh Tuan Hoang is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • WordPress provides a bunch of handy {timespan}_IN_SECONDS constants so you don't need to remember, eg, that there are 86,400 seconds in a day. (Unless you like singing that song from Rent to yourself, of course.) You can replace 86400 with DAY_IN_SECONDS, for example. They're in wp-includes/default-constants.php and they include MINUTE_IN_SECONDS, HOUR_IN_SECONDS, DAY_IN_SECONDS, WEEK_IN_SECONDS, MONTH_IN_SECONDS, and YEAR_IN_SECONDS.
    – Pat J
    Commented 2 hours ago

Not the answer you're looking for? Browse other questions tagged or ask your own question.