I have a web application which get a date ( dd.mm.YYYY
) from a MySQL database.
$date = ($_row["date"]);
$date = date('d.m.Y', strtotime($date));
$date = date('d.m.Y', strtotime("-5 day", strtotime($date)));
I format the date like this.
Now i want to compare the date from the DB with the date today.
$today = date('d.m.Y');
I want to show something when in 5 days from today is $date
. My question is now how can I check this? I know there are many mistakes in the codes but I don't know how to do this correctly.
you can use the datetime object with function diff(). min. PHP 5.3.0
it is very comfortable:
<?php
// your date from your Database
$date = new DateTime('26.01.2015');
// today
$today = new DateTime;
// calculate difference
$diff = $today->diff($date);
// if difference = 5 days
if($diff->format('%a') == 5) {
echo '5 days away';
}else{
echo $diff->format('%a'). ' days away.';
}
?>
if you have a php version LESS 5.3.0 you can use the function of stepozer in the other answer:
<?php
$_row["date"] = '27.01.2015';
// your date from your Database
$date = new DateTime( $_row["date"]);
// today
$today = new DateTime;
// if difference = 5 days
if(dateDifferenceInDays($date->format('d.m.Y'), $today->format('d.m.Y')) == 5){
echo '5 days';
}
// function from stepozer
function dateDifferenceInDays($date1, $date2)
{
$str = strtotime($date1) - strtotime($date2);
return floor($str / 3600 / 24);
}
?>
You can use strtotime like this:
public static function dateDifferenceInDays($date1, $date2)
{
$str = strtotime($date1) - strtotime($date2);
return floor($str / 3600 / 24);
}
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.