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']);
Related
Using WIndows, XAMPP 5.6.8 I am building a simple web app in HTML and PHP.
I would like to compare a date retrieved from a database with today's date.
I have a function that successfully returns a string value (in the UK date format d-m-y).
My code so far is;
$expDate = get_api_data($id); // returns a string
var_dump($expDate); // this prints string(8) "31-12-19"
Using this $expDate value I would like to achieve something like;
if (strtotime('d-m-y', $expDate) > time()) { // if date > than today
echo 'date is greater than today';
}
elseif (strtotime('d-m-y', $expDate) < time()) { // if date < than today
echo 'date is less than today';
}
else {
echo 'date not found';
}
Currently I am receiving date is less than today - even though the date is 31-12-19. I'm not sure if I am approaching this the correct way?
Any help would be greatly appreciated as I have alreday spent a lot of time researching answers to no avail.
I got this error when executing your code
PHP Notice: A non well formed numeric value encountered
You should look at the doc in order to make a good usage of this function: http://php.net/manual/fr/function.strtotime.php
The first param should be a time, not a format.
By the way, i prefer use DateTime class to compare dates, you can do:
<?php
$expectedDate = \DateTime::createFromFormat('d-m-y', get_api_data($id));
$nowDate = new \DateTime();
if ($expectedDate > $nowDate) { // if date > than today
echo 'date is greater than today';
}
elseif ($expectedDate < $nowDate) { // if date < than today
echo 'date is less than today';
}
else {
echo 'date not found';
}
$formattedDate = DateTime::createFromFormat('d-m-y', $expDate);
$expDate= $formattedDate->getTimestamp();
if ($expDate > time()) { // if date > than today
echo 'date is greater than today';
.....
Try above code sample, try to use DateTime class if you have PHP 5.2.0 or higher http://php.net/manual/en/datetime.createfromformat.php . Then using that dateTime object you can do comparisons in a way you want e.g. in my sample I am doing it by time.
Your code will show a notice. if you turn on the php error reporting, you will observer it.
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
The date to be checked is as follows :
$submission_date = 12-25-2014; //The date in mm-dd-yyyy format that is to be tested against today's date
Now I want to echo the error message since the date contained in a variable $submission_date is a future date.
How should I do this efficiently and effectively using PHP?
Thanks in advance.
Many ways to do this (use DateTime::createFromFormat() to control exact format of input dates, for example) but perhaps the simplest that suits the example is:
$isFuture = (strtotime($submission_date) > strtotime($_POST['current_date']))
Note that OP changed the question. If desired date to test against is not in $_POST array, just replace strtotime($_POST['current_date']) with time() to use current system time.
To compare against current date, disregarding time of day, use:
$today = new DateTime(date("Y-m-d"));
// $today = new DateTime("today"); // better solution courtesy of Glavić
// see http://php.net/manual/en/datetime.formats.relative.php for more info
$today_timestamp = $today->getTimestamp();
If posted format is in m-d-Y, then you cannot convert it to unix timestamp directly with strtotime() function, because it will return false.
If you need to use strtotime() then change the input format to m/d/Y by simple str_replace().
On the other hand, you could use DateTime class, where you can directly compare objects:
$submission_date = DateTime::createFromFormat('!m-d-Y', $submission_date);
$today_date = new DateTime('today');
if ($submission_date > $today_date) {
echo "submission_date is in the future\n";
}
demo
With PHP DateTime you can check whether the input date is future or old w.r.to the todate.
$submission_date = DateTime::createFromFormat('m-d-Y', $submission_date);
$submission_date = $submission_date->format('Y-m-d');
$current_date = new DateTime('today');
$current_date = $current_date->format('Y-m-d');
if ($submission_date > $current_date)
{
echo "Future date";
}
else
{
echo "Old date";
}
Im having some bizarre results in regards to the php date() function. Basically Im getting a date from a Mysql database which is in a string format, split into three elements. This would be Day, Month, Year (15 september 2012 for example) Im ultimately comparing two dates to see if it has expired. But the issue is that only certain dates are allowing the code to work, and some do not work at all (or allow the if statement to work effectively) Below is my code, any help would be great.
$today = date("d-m-Y");
$expire = date("d-m-Y",strtotime($this->getData('date_day')."-".
$this->getData('date_month')."-".$this->getData('date_year'))) ;
if ($expire < $today)
{
echo 'expired';
}
else
{
echo 'Not expired';
}
Im sure its something simple, but for some reason I cannot solve it.
You need to compare the Unix timestamps.
$today = time();
$expire = strtotime($this->getData('date_day')."-".
$this->getData('date_month')."-".$this->getData('date_year')) ;
if ($expire > $today)
{
echo 'expired';
}
else
{
echo 'Not expired';
}
It looks like strtotime is expected a US date format; you need to swap the month and the day around to generate a valid date:
$today = date("d-m-Y");
$expire = date("d-m-Y",strtotime($this->getData('date_month')."-".
$this->getData('date_day')."-".$this->getData('date_year'))) ;
On the other hand, see Stephen305's answer - it's a much better solution to your problem.
I have a date returned from an sql query (a datetime type field) and want to compare it to today's date in PHP. I have consulted php manual and there are many ways to do it. I finally came up with a solution comparing strings, but I would like to know if there are either any 'better' (best practice), cleaner or faster ways to do it. This is my solution:
// $sql_returned_date='2008-10-17 11:20:04'
$today = new DateTime("now");
$f_today=$today->format('Y-m-d'); //formated today = '2011-03-09'
$sql_date=substr($sql_returned_date,0,9); //I get substring '2008-10-17'
if($f_today==$sql_date)
{
echo "yes,it's today";
}else{
echo "no, it's not";
}
thanks
Seriously guys?
//$mysql_date_string= '2013-09-20' OR '2013-09-20 12:30:23', for example
$my_date = new DateTime($mysql_date_string);
if($my_date->format('Y-m-d') == date('Y-m-d')) {
//it's today, let's make ginger snaps
}
You could factor this into the data returned from your database query:
SELECT `DateOnDB`,
DATE(`DateOnDB`) = DATE(CURDATE()) AS isToday
FROM `dbTable`
and simply use PHP to test the value of the isToday column
Excuse me for being a question-digger, but I was trying to achieve the same thing, and I found a simple solution - if you want to select only rows with today's date you can do :
WHERE DATE(datetime_column)=CURDATE()
in your mySQL query syntax.
You'd have three solutions :
Working with strings, like you are doing ; which seems like a solution that works ; even if it doesn't feel clean.
Working with timestamps, using strtotime() and time() ; which is a bad idea : UNIX Timestamps only work for dates that are greater than 1970 and lower than 2038
Working with DateTime everywhere ; which would both work and feel clean.
If I need to make any calculation on the PHP-side, I would probably go with the third solution -- but the first one would be OK in most cases, I suppose.
As a sidenote : instead of formating your date to Y-m-d, you could check if it's :
Greater of equal than today
Less than tomorrow.
If SQL returned date is in this format 2011-03-09 (date format without timing),
$sqlret = "2011-03-05";
$curdate = date('Y-m-d');
echo $diff = strtotime($curdate) - strtotime($sqlret);
echo $no_diff = $diff/(60*60*24);
If the date with time like:
$sqlret = "2011-03-05 12:05:05",
Just make your current date format also like that:
$curdate = date('Y-m-d H:i:s');
If it doesn't satisfies your need, ask your question with some example.
You can use new DateTime php Object that way.
$date1 = new DateTime('2012-01-21');
$date2 = new DateTime ( 'now');
$interval = $date1->diff($date2);
if( $interval->format('%R%a ') == 0){
echo 'it s today';
}
I'd do that:
# SQL
SELECT DATE_FORMAT(date_col, "%Y-%m-%d") AS created_at FROM table
# PHP
if ( date('Y-m-d') == $sql_date ) { // assuming $sql_date is SQL's created_at
echo 'today';
}
$time = //your timestamp
$start = mktime(0,0,0,date("j"),date("n"),date("Y"));
$end = mktime(23,59,0,date("j"),date("n"),date("Y"));
if($time > $start && $time < $end){
//is today
}