BeTA iT BeTA iT - 1 year ago 78
PHP Question

Show content based on date (date before, date after, date between)

This is setup to show a button between 2 dates set. And to show a "Sign up starts at xxx" before the set start up date, and "Sign up closed the xxxx" after the set end date...

Somehow nothing shows for the "active periode" / the dates in betweeen...

$DateToday = date('Ymd');
$DateStart = get_field('pamelding_fra');
$DateEnd = get_field('pamelding_slutt');
$DateStartOut = new DateTime($DateStart);
$DateEndOut = new DateTime($DateEnd);

if ($DateStart >= $DateToday){

$ClassStatus = "<div class=\"OpenClassButton\"><span class=\"ClassFullWarning\">Påmeldingen åpner " . $DateStartOut->format('j M Y') . "</span></div>";
$ClassButton = $ClassStatus;

}elseif ($DateEnd <= $DateToday){

$ClassStatus = "<div class=\"OpenClassButton\"><span class=\"ClassFullWarning\">Påmeldingen stengte " . $DateEndOut->format('j M Y') . "</span></div>";
$ClassButton = $ClassStatus;

}elseif ($DateStart <= $DateToday && $DateEnd >= $DateToday){

//Do some stuff - show button, this is the active time.

Might not be best-practice and I might make stuff difficult for me, suggestions appriciated.

Answer Source

Don't compare dates using date strings. If they are in different formats (like Ymd, mdY etc) you will get unwanted results. Use unix timestamps instead.

$today = time(); // Get today's timestamp

if ($today < strtotime($DateStart)) {
    // Do stuff before
} elseif ($today > strtotime($DateEnd)) {
    // Do stuff after
} else {
    // Active. No need for any conditions here,
    // since we only have three states.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download