如何限制日期和时间之间的访问?

时间:2015-12-19 12:36:05

标签: php date time visible

我喜欢添加php脚本,仅允许帖子,在这些日子和时间之间发表评论:

Monday-Friday: 09.00 - 19.00
Saturday: 10.00-15.00

所有其他时间的帖子功能都不可用。我是怎么做到的?

从此开始,但后来我意识到我还需要几天时间:

<?php date_default_timezone_set('Europe/Stockholm'); // NDT 
$startTime = '09:00'; //opening hours starts
$endTime = '14:00'; //closing hours 
$time = new DateTime($startTime); 
$time1 = date_format($time, 'H:i'); 
$time = new DateTime($endTime); 
$time2 = date_format($time, 'H:i');

"Today is " . $current =date("H:i") . "<br>";

if ($current > $time1 && $current < $time2) {
     echo 'The pposting is closed from 13.00 - 09.00. Sorry for the Inconvenience.'; }
else{
   echo "It's open";
}

1 个答案:

答案 0 :(得分:0)

您可以使用date_default_timezone_set功能设置所有日期/时间功能使用的默认时区。 (取自手册)

要从DateTime指定所需的格式,您可以使用format方法。此示例中用于格式化方法的字符取自date

你可以做的是通过使用&#39; N&#39;来获取星期几。对于格式,然后检查它是工作日还是星期六。

  

N ISO-8601星期几的数字表示(添加于   PHP 5.1.0)1(星期一)到7(星期日)

然后检查工作日或星期六的开始/结束时间是否打开或关闭并显示您的信息。

用于显示我已使用sprintf的消息。

也许此设置可以帮助您:

<?php
date_default_timezone_set('Europe/Stockholm');
function displayAllowPostsMessage($dateTime)
{
    $weekdayStartTime = new DateTime('09:00');
    $weekdayEndTime = new DateTime('19:00');
    $saturdayStartTime = new DateTime('10:00');
    $saturdayEndTime = new DateTime('15:00');
    $templateOpen = "It's %s and we are open!";
    $templateClosed = "It's %s and the posting are only allowed between %s - %s. Sorry for the Inconvenience.";
    $dayOfTheWeek = intval($dateTime->format('N'));
    $message = "It's closed on sunday.";

    // On a weekday
    if ($dayOfTheWeek < 6) {
        $isOpen = $dateTime > $weekdayStartTime && $dateTime < $weekdayEndTime;
        $message = sprintf(
            $templateOpen,
            $dateTime->format('l H:i')
        );
        if (!$isOpen) {
            $message = sprintf(
                $templateClosed,
                $dateTime->format('l H:i'),
                $weekdayStartTime->format("H:i"),
                $weekdayEndTime->format("H:i")
            );
        }
    }

    // On a saturday
    if ($dayOfTheWeek === 6) {
        $isOpen = $dateTime > $saturdayStartTime && $dateTime < $saturdayEndTime;
        $message = sprintf(
            $templateOpen,
            $dateTime->format('l H:i')
        );
        if (!$isOpen) {
            $message = sprintf(
                $templateClosed,
                $dateTime->format('l H:i'),
                $saturdayStartTime->format("H:i"),
                $saturdayEndTime->format("H:i")
            );
        }
    }
    echo $message;
}

displayAllowPostsMessage(new DateTime());

Demo with added debug code to test different days