2

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

4

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';
}

Note: As per Pat J's comment, WordPress provides a bunch of handy {timespan}_IN_SECONDS constants in wp-includes/default-constants.php, including DAY_IN_SECONDS.

So in the above code, floor( $rem_days / 86400 ) can be replaced with floor( $rem_days / DAY_IN_SECONDS )

3
  • 2
    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 Sep 19 at 20:13
  • 2
    That maybe depends on the developer actually. Personally, I know one hour has 3600 seconds, and one day has 86400 seconds, but I didn't know that we have those constants given in WordPress. But thanks for your suggestion. I updated the answer to include that for future references. Commented Sep 20 at 0:24
  • 1
    It worked like a charm, It was easy for me to understand by numbers but I did learnt new thing about these constants. Thanks to @AnhTuanHoang and Pat J Commented Sep 20 at 5:28

Your Answer

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

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