Thanks to the answers to this question, I've managed to only output a list dates from my MySQL database that are in the future (ie after today) using PHP. However, what if I wanted to set 'today' back a little; in other words, if I want a date not to appear on the list of dates a week in advance?
I've attempted to use DateTime::sub using the following code, but it kills my script (I just get a blank screen - if I comment out the DateTime::sub line, it works again. I still haven't worked out how to get PDO to echo error details):
$dateToday = new DateTime('now');
$dateToday -> sub(new DateInterval('P7D'));
do{
$dateCompare = new DateTime($row['date']);
if ($dateCompare > $dateToday){
echo '<p>'.$dateCompare -> format('Y-m-d').'</p>';
} else {
echo '<p>FALSE</p>';
}
}while ($row = $stmt->fetch(PDO::FETCH_ASSOC));
Any ideas?
You code works just fine for me, I imagine it's a problem with this line:
$dateCompare = new DateTime($row['date']);
What format is the $row's date in?
I'd recommend using
$date = DateTime::createFromFormat('The format your dates are in', $row['date']);
See http://www.php.net/manual/en/function.date.php for possible date formats
e.g. Y-m-d would parse 2012-10-28
If you have an older version of PHP, you could try this "low tech" solution by comparing as strings.
// Assuming your mysql is Y-m-d
$dateToday = date('Y-m-d')
do{
if ($row['date'] > $dateToday){
echo '<p>'.$dateCompare -> format('Y-m-d').'</p>';
} else {
echo '<p>FALSE</p>';
}
while...
Related
I've created an If an Else Statement but it doesn't work properly.
I have some dates within my SQL which have been retrieved and stored in variables using PHP.
I'm comparing the current date with the dates from the database but for some reason, it thinks for example that 29-09-2015 if LESS THAN 31-01-2015.
I can understand that the format could be the issue d,m,Y but I thought I'd corrected that already.
Here's the code:
$today = date('d-m-Y');
$date = $row['respondby'];
$euDate= date("d-m-Y", strtotime($date));
<?php
if($today < $euDate){ echo "<td>". $today." is less than ". $euDate ."</td>";
}
else{
echo"<td>Lost somewhere in between ?!?!?! :S </td>";
}
?>
As a result it prints
29-09-2015 is less than 30-06-2015
today's date was 29-09-2015 and one of the dates was in the data was this one as shown.
Thank you everyone that helps.
Comparison of dates as strings uses lexicographical order, hence your result is "correct".
Instead of d-m-Y format, try to use Y-m-d, this guarantees proper ordering.
$today = date('Y-m-d');
$date = $row['respondby'];
$euDate= date("Y-m-d", strtotime($date));
if($today < $euDate) { [...] }
Or, you can use Date objects instead:
$today = new Date('now');
$euDate= new Date($row['respondby']);
if($today < $euDate) { [...] }
I am working on a php app and need some help with comparing a date.
I have a date select input field (datepicker) which thanks to client side code will always post a date in the format: mm/dd/YYYY eg 02/25/2015.
What Iam trying to do is assertain that this date is no later than the current date, using php.
Initially I have set the local timezone with:
date_default_timezone_set('Europe/London');
And within the code I have:
} elseif (date(strtotime($_POST['datepicker'])) > date('m,d,Y')){
$displayblock.= "<br><p>The selected date is in the future!!! </p>".date("d/m/Y", strtotime($_POST['datepicker']));
$alertbox = "<script>alert('".$_POST['datepicker']." is in the future!!! Shall we try that again? :-)');</script>";
This is obviously far from graceful and does not appear to be comaparing dates correctly either.
Can anyone help pls?
Many Thanks,
You can also compare them if they are coming as a string with this function. The first date is your date coming from your html/javascript datepicker, the second date is the actual date of server:
function stringDateIsAPastDate($datestring1){
if ((date("j-m-Y", strtotime($datestring1))) <= (date("j-m-Y"))){
//here the code to do when the date inserted from the website is a past date or today
return(true);
}else{
return(false);
}
}
$now = new DateTime();
$now->format('Y-m-d');
$ding = new DateTime($_POST['datepicker']);
$ding->format('Y-m-d');
if($now < $ding){
echo 'datepicker is after current time';
} else {
echo 'datepicker is before current time';
}
Compare Two Dates
$date1 = new DateTime('May 13th, 1986');
$date2 = new DateTime('October 28th, 1989');
$difference = $date1->diff($date2);
Check this :
http://www.paulund.co.uk/datetime-php
And php.net Manual:
http://php.net/manual/en/class.datetime.php
I have a MySQL database with a list of dates. I want to output all these dates, provided they occur after today, into a page. The dates are stored in the database in DATE format, as Y-m-d.
I've got the following code (excluding the query etc):
$dateToday = date('Y-m-d');
do{
$dateCompare = new DateTime($row['date']);
if ($dateCompare > $dateToday){
echo '<p>'.$dateCompare -> format('Y-m-d').'</p>';
} else {
echo '<p>FALSE</p>';
}
}while ($row = $stmt->fetch(PDO::FETCH_ASSOC));
But this just outputs all the dates, including one I have set in the past for testing purposes. What am I doing wrong?
$dateToday is a string. $dateCompare is a DateTime object.
You should use strtotime() function.
http://www.w3schools.com/php/func_date_strtotime.asp
Try and convert the date from myssql to a datetime object and output.
$changetime = new DateTime($time, new DateTimeZone('UTC'));
ECHO $changetime->format('m/d/y h:i a');
// list of timezones http://us1.php.net/manual/en/timezones.php
I actually use this to output all my MYSQL datetime data - allows me to convert to any timezone. Note, this will assume your datetime is in UTC - you should convert to your timezone.
$stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach ($stmt as $row) {
$time = strtotime($row['date']);
if ($_SERVER['REQUEST_TIME'] - $time) {
echo '<p>'. date('Y-m-d', $time) . '</p>';
} else {
echo '<p>FALSE</p>';
}
}
I got a pretty simple code that will take 2 dates and loop my data until the end date is reached.
$start = new DateTime($senddate);
$now = new DateTime("NOW");
$end = new DateTime ($end);
//We check if starting date is >= now()
if ($start->date <= $now->date){
$start = $now;
}
$i=0;
if ($frequency==4){
while ($start->date <= $end->date) {
$calcdate[$i]=$start->date;
$start->modify('+1 month');
$i++;
echo '<!--';
print_r($start);
echo '-->';
}
As you see there is a print_r inside the loop.
Everything work fine :)
BUT, if I remove it, then the loop never end .. I tried to add if($i>50) exit; without anymore success. I don't understand why this loop doesn't work when no pint_r is inside.
Thanks for your help
I would suggest that you have a read of the PHP DateTime manual, there is a lot of good information there that will help you with what you are trying to do.
As far as I can tell, you are trying to carry out an operation on a monthly basis between two dates that span the current date. There is a simpler way of doing it utilising the DatePeriod class.
Something like this:-
$start = new \DateTime('yesterday');// Just for demo purposes
$now = new \DateTime(); //No need for "now" as it is the default
$end = new \DateTime('+ 6 month');// again, for demo purposes
$interval = new \DateInterval('P1M');
if($now >= $start){ // you can do direct comparisons on DateTime objects
$period = new \DatePeriod($start, $interval, $end);
foreach($period as $date){
// Each $date is a DateTime instance that you can
// operate on as you see fit, I have just var_dumped it out.
var_dump($date);
}
}
The above code can be seen working here http://3v4l.org/1I30E
My error came from this line $calcdate[$i]=$start->date;
It seems that this gives somme unexpected behavior (in this case), I tried using $calcdate[]=$start->format('Y-m-d H:i:s'); which gave the expected results ... Don't know why my script didn't worked with the date method. If anyone knows ..
I am using the following code to attempt to compare the current date with a date entry in a mySql database. It's code that I have found online and adapted as all the examples I have found hard-code the date to compare the current date with.
The trouble is even dates in the future are being marked as expired and I can't understand why this would be.
I am afraid that I am still new to PHP, so I may be making a schoolboy error!
$exp_date = KT_formatDate($row_issue_whatson1['dateToShow']);
$todays_date = date("d-m-Y");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) { echo "Not expired"; } else { echo "expired"; }
Any help would be most appreciated.
I should add that the date time format used in the database entries is dd/mm/yyyy
Instead of making a string then converting it to a timestamp, simply use mktime:
<?php
$today = mktime(
0, // hour
0, // minute
0 // seconds
);
?>
The rest of the values will be filled according to today's date. If this still gives problems, put in some echo's for the values of $exp_date and $expiration_date.
Edit
Since this solved the problem, the discrepancy you were seeing was because you were doing the opposite with date('d-m-Y'). You were asking for the current date and the time values are then filled in with the current time. The expiration date in the database is likely set at midnight. With both dates being equal, and it being say 11am now, you are comparing if (00:00:00 > 11:00:00) which fails.
$exp_date = 14/05/2011 // todays date, int
$server_date = server.date() // servers date, int
// check exp_date against server date
if ( $server > $exp_date)
{ echo "Sorry your 'service' has expired"; }
else
{ echo "Welcome 'members_name' to StackOverflow"; }
Try that. However you need the right date format, as server.date() is probably different in PHP.
If problem still persists I would check whether your dates are strings or integers or both. That could possibly be the issue.
Hope that helps.
DL.
Your function does not seem to be valid.
function KT_formatDate( $exp_date){
$exp_date = strtotime($exp_date);
$now = time();
if ($now > $exp_date)
return 'expired';
else
return ' Not expired';
}
$response = KT_formatDate($row_issue_whatson1['dateToShow']);