PHP date comparison and strtotime - php

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.

Related

Check validation if date is < 3 months

i want to get a validation from this case. If the entry date is less than now. So it would result an alert and redirect to the homepage. I wrote this one but it didn't work.
$dateEntry = array($current_employee->emp_dtentry);
if ($dateEntry < strtotime('+3 months')) {
echo "<script>alert('you don't have the right to access this menu')</script>";
redirect('new_leave','refresh');
}
Will appreciate any help, thanks before!
You are putting your date into an array and then comparing it to a timestamp. Why are you doing that?
Assuming $current_employee->emp_dtentry is a Unix timestamp:
if ($current_employee->emp_dtentry < strtotime('+3 months')) {
If it is not a Unix timestamp and is a valid date format you can do:
if (strtotime($current_employee->emp_dtentry) < strtotime('+3 months')) {
If it is not a valid date format you would need to use DateTime::createFromFormat() to parse the date and then do your comparison. That is easier to do with DateTime objects throughout.
// see manual format options
$empdtEntry = DateTime::createFromFormat('<format goes here>', ($current_employee->emp_dtentry);
$current_employee->emp_dtentry);
$threeMonthsFromNow = new DateTime(+3 months);
if ($empdtEntry < $threeMonthsFromNow ) {
As you are redirecting, your echo won't work. Either flash your javascript or use javascript there to redirect too.
Using flash:
$dateEntry = $current_employee->emp_dtentry;
if ($dateEntry < strtotime('+3 months')) {
$this->session->set_flashdata("javascript", "<script>alert('you don't have the right to access this menu')</script>");
redirect('new_leave');
}
Then within the new_leave view check it if exists and echo it:
if($this->session->flashdata('javascript')){
echo $this->session->flashdata('javascript');
}
Or using javascript do it as below:
$dateEntry = $current_employee->emp_dtentry;
if ($dateEntry < strtotime('+3 months')) {
echo "<script>alert('you don't have the right to access this menu'); window.location.href='new_leave';</script>";
}

Check if older or newer date than current (by month)

I want to check if given date (like 2012-12) is older or newer than current date.
I know how to check older month like
if(strtotime('2012-12')<strtotime('-1 Months')){
echo "true"; // got TRUE ... correct!
} else {
echo "false";
}
But what about newer ?
if(strtotime('2013-02')>strtotime('1 Months')){
echo "true";
} else {
echo "false"; // got FALSE ... incorrect !
}
I got incorrect result when checking newer date.
You forgot to add the + to your strtotime function.
if(strtotime('2013-02')>strtotime('+1 Months')){
echo "true";
} else {
echo "false";
}
Update:
Some things are weird in your question. For example 2013-02 is not a date but a reference to a month. If you want to check if this is the first day of the month use the full date notation: 2012-02-01. If you want to check if the current date into a month check the current month with date("n") (returns 1-12); and compare this to the given month, for example:
$date = "2012/02/01";
if(date("n", strtotime($date)) != date("n")) {
echo 'not current month';
}
if you want to check if this is not the current date do something like:
$date = "2012/02/01";
if(date('d-m-Y', strtotime($date)) != date('d-m-Y')) {
echo 'not current day';
}
If you want to compare a date with the current time to see if its in the past or in the future you could use
$date = '2013-02';
$now = time();
if ( strtotime($date) > $now ) {
echo 'Date is in the future';
} else {
echo 'Date is in the past';
}
Note however that if you supply a date like $date = '2013-01' i.e. without a day it will return as in the past, even though we are still in january. Be sure to take a look if this is the behaviour you want
What about comparing the strings? If you can compare directly the strings, using the ISO 8601 format yyyy-mm-dd they're always lexicographically ordered.
2012-01 < 2012-12 < 2013-01 < 2013-02 < 2014-01
(the bold one being the current)

Odd Date("Y-m-d") result

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.

Comparing a date to current server date using PHP

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']);

check if datetime from sql is today

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
}

Categories