根据日期显示内容(日期之前,日期之后,日期之间)

时间:2016-11-02 15:40:12

标签: php date

这是设置为显示设置的2个日期之间的按钮。并显示"注册开始于xxx"在设置启动日期之前,"注册关闭xxxx"在设定的结束日期之后......

以某种方式没有显示"活跃的周期" /在......之间的日期......

$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.    
 }

可能不是最好的练习,我可能会让事情变得困难,建议很有用。

1 个答案:

答案 0 :(得分:0)

不要使用日期字符串比较日期。如果它们采用不同的格式(例如YmdmdY等),您将收到不需要的结果。改为使用unix时间戳。

$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.
}