PHP: Conditional based on date
I have a date like this: 16/02/2011
What I want to do is have a simple PHP conditional that checks if 开发者_JS百科todays date is either that DAY or AFTER so for example:
<?php
$mydate = '26/01/2010';
if($mydate == date('dd/mm/yyyy')
{
echo 'last day to reply';
}
elseif($mydate == 'date after todays date')
{
echo 'post has expired and you cannot reply';
}
else
{
echo 'post has NOT expired and you can reply';
}
?>
So if today's date is 01/01/2011 then it would say post has not expired if date is 17/02/2011 then it would say last day to reply and if the date is after 25/02/2011 then it would say it has expired.
Can anyone help? Thanks :)
The easiest way would be to use mktime to convert the required date and times (the last date and the ultimate deadline) and then directly compare the current time against the those.
the easiest way is to have a date already in the proper format. Especially if it's coming from database.
<?php
$mydate = '2010-01-26';
$curdate = date('Y-m-d');
if($curdate == $mydate)
{
echo 'last day to reply';
}
elseif($curdate > $mydate)
{
echo 'post has expired and you cannot reply';
}
else
{
echo 'post has NOT expired and you can reply';
}
?>
note that by reading this code you will have no problem understanding what does it do.
it's almost natural language and self-explanatory
unlike all other codes here.
Rather than compare visual dates it's probably better to compare timestamps:
$deadline = strtotime('2010-01-26');
$today = mktime(0, 0, 0);
if ($today == $deadline) {
echo 'last day';
}
else if ($today > $deadline) {
echo 'past day';
}
else {
echo 'a-okay';
}
In simplistic terms, you'd want to do somethinn like:
if (strtotime($date) > date()) { echo "Your post has expired"; }
it's very difficult to compare dates-that-are-strings, especially when you consider that "2/3/4" could be any of 8 different dates (Feb 3rd, '04; Mar 4th, '02; etc..). Keeping dates/times as actual timestamp values in PHP makes the comparisons far easier.
You can use mktime
(or strotime
if you can get your end date in a proper format, 17-02-2011 or 02/17/2011):
$mydate = '17/02/2011';
$mydate_parts = explode('/', $mydate);
$mydate_timestamp = mktime(0, 0, 0, $mydate_parts[1], $mydate_parts[0], $mydate_parts[2]);
if($mydate == date('d/m/Y'))
{
echo 'last day to reply';
}
elseif($mydate_timestamp < time())
{
echo 'post has expired and you cannot reply';
}
else
{
echo 'post has NOT expired and you can reply';
}
I would strongly recommend you look up on the DateTime class documentation; if you're not interested though; a string slice would work.
Something along the lines of the following is probably the quickest for you.
if( mktime(0,0,0,substr($mydate, 3, 2), substr($mydate, 0, 2), substr($mydate, 6, 4) ) > time() )
精彩评论