简体   繁体   中英

PHP - Check if user's entered date is of future or of today

I have a textbox to enter Date.

What should the code look like to check if the user's entered date is of future or of today?

I also want the users' to enter date in dd/mm/yyyy format.

The code will give an error if any of them fails.

You can use the DateTime class to do this comparison as well:

$now       = new DateTime();
$user_date = DateTime::createFromFormat('d/m/Y', $userDate);
if ($user_date >= $now)
{
     echo 'Date is not in the past';   
}

use

int mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second = date("s") [, int $month = date("n") [, int $day = date("j") [, int $year = date("Y") [, int $is_dst = -1 ]]]]]]] )

from manual page

so fill in the parameters and subtract

time()

if it's greater than zero, it's in the future

I recommend this solution:

/**
 * Is future date
 *
 * Checks if given date is today
 * or in the future.
 *
 * @param string $date
 *
 *
 * @return bool
 *
 */
protected function isFutureDate($date)
{
    // assuming the date is in this format
    // (I use value objects for these things so that
    // I don't have to repeat myself)

    $date = DateTimeImmutable::createFromFormat('d-m-Y', $date);
    $today = DateTimeImmutable::createFromMutable(new DateTime());
    return $date->getTimestamp() >= $today->getTimestamp();
}

I use the following Date object which is extended by any other date class. Other date classes will have their own rules (such as date must be in future etc...) which extend from this base class:

/**
 * Class DateValueObject
 *
 * 
 *
 * @package Hidden\Model\Shared\ValueObject
 *
 */
abstract class DateValueObject extends ValueObject
    implements DateValueObjectContract
{

    /**
     * @var DateValueObject
     *
     */
    protected $value;


    /**
     * Initialises the Date.
     *
     * @param $date
     *
     * @throws InvalidDateException
     *
     */
    public function __construct($date)
    {
        if (is_string($date)) {
            $this->value = $this->setDate($date);
        } else {
            throw new InvalidDateException(
                'String Expected. Got: ' .$date
            );
        }
    }


    /**
     * Set valid date.
     *
     * @param string $date
     *
     * @return DateTimeImmutable
     *
     * @throws InvalidDateException
     */
    protected function setDate($date)
    {
        try {
            $d = DateTimeImmutable::createFromFormat('d-m-Y', $date);
            if($d && $d->format('d-m-Y') == $date) {
                return $d;
            } else {
                $d = DateTimeImmutable::createFromFormat('d/m/Y', $date);
                if($d && $d->format('d/m/Y') == $date) {
                    return $d;
                }
                throw new InvalidDateException(
                    'Date cannot be formatted: ' .$date
                );
            }
        } catch (\Exception $e) {
            throw new InvalidDateException(
                'For date: ' .$date .' with message' .$e->getMessage()
            );
        }
    }



    /**
     * Get the date to string
     *
     * @param string $format
     *
     * @return string
     *
     */
    public function toString($format = 'd/m/Y')
    {
        return $this->value->format($format);
    }


    /**
     * Get the date as immutable object.
     *
     *
     * @return DateTimeImmutable|Date
     *
     */
    public function toDateObject()
    {
        return $this->value;
    }
}

EDIT: Please note that the first block of code checks if the date is in the future or not, while the second example is for having an extendible class so that other date classes (Birthday, InvoiceDate etc..) can extend from without having to repeat the code. You can put this in a method instead and keep copy and pasting it every time you need it or else just extend from it, knowing it works across the board.

My example accepts both "dmY" and "d/m/Y" and handles the formats accordingly. At the end of the day, you still have a php DateTimeImmutable object but one which knows how to build itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM