admin管理员组

文章数量:1122832

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.

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.

Share Improve this question edited Sep 19, 2024 at 16:22 Anh Tuan Hoang 1886 bronze badges asked Sep 19, 2024 at 6:23 Milan BastolaMilan Bastola 2972 gold badges4 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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 )

本文标签: phpDate not working correctly