How to compare single date with multiple dates in PHP - php

How do i compare two dates in php?.
I have the following dates. One is coming from DB. and another is from Datepicker
$dbdate = 01-06-201402-06-201403-04-201405-06-2014 //DB date
$datepickerDate = 06-06-2014 //Datepicker date.
Here $dbdate is in foreach loop and both formats are dd-mm-yyyy. How do i compare a single date from datepicker to the date in $dbdate?

Compare with STRTOTIME function in for loop like this
return STRTOTIME($dbdate) === STRTOTIME($datepickerDate);

best thing is convert all to unix time stamp..
php method is strtotime()
then it return integer value...u can compare that values
http://www.php.net//manual/en/function.strtotime.php
but the thing is ur dbdate parsing more than 1 date at a time..u should get 1 date at a time

This is not an ideal solution - but I hope it helps you out ;-).
<?php
// Input
$dbdate = '01-06-201402-06-201403-04-201405-06-2014';
$datepickerDate = '06-06-2014';
// Please note: it would be possible to check dates directly in this for loop.
// For educational purposes I splitted it.
$datepickerDateTime = strtotime($datepickerDate);
// Transform concatenated dates to separate dates in array.
$datesList = array();
$dateOffset = 10;
for($iCurrentDateOffset = 0; $iCurrentDateOffset < strlen($dbdate); $iCurrentDateOffset += $dateOffset) {
$datesList[] = substr($dbdate, $iCurrentDateOffset, $dateOffset);
}
// Compare each separate date to $datepickerDate
foreach($datesList as $date) {
if(strtotime($date) < $datepickerDateTime) {
echo("$date is before $datepickerDate<br />");
} else if(strtotime($date) == $datepickerDateTime) {
echo("$date is equal to $datepickerDate<br />");
} else if(strtotime($date) > $datepickerDateTime) {
echo("$date is past $datepickerDate<br />");
}
}
// ...
Output is:
01-06-2014 is before 06-06-2014
02-06-2014 is before 06-06-2014
03-04-2014 is before 06-06-2014
05-06-2014 is before 06-06-2014

Related

PHP Datetime check date with different format

I've got a problem with datetime condition checked.
First, I've a DateTime value that stored in database as 2018-05-08 15:54:40
But, I want to check only date is equal or not.
For example:
$DateInDatabase = 2018-05-08 15:54:40
$DateSpecific = 2018-05-08
if ($DateInDatabase == $DateSpecific) {
......
}
The question is how to check only date in $DateInDatabase
If you are only interested in the year-month-day, my suggestion would be something such as;
// As per comments, the second param in the date function MUST be a UNIX timestamp, so strtotime will resolve this
$dateInDB = date("Y-m-d", strtotime($DateInDatabase)); // format to XXXX-XX-XX
$dateToCheck = date("Y-m-d", strtotime($DateSpecific)); // format to XXXX-XX-XX
if ($dateInDb == $dateToCheck)
{
// They are the same
}
else
{
// The are different
}
As others have said, you can use direct string comparison also;
$DateInDatabase = "2018-05-08 15:54:40";
$DateSpecific = "2018-05-08";
// This function uses the params haystack, needle in that order
if (stristr($DateInDatabase, $DateSpecific))
{
// Match found
}
else
{
// No match found
}
You can use php date method to format date:
$DateInDatabase ='2018-05-08 15:54:40';
$DateSpecific = '2018-05-08';
if (date('Y-m-d', strtotime($DateInDatabase)) == $DateSpecific) {
echo 'ok';
} else {
echo 'not ok';
}
Read more about php date method from here
You can either directly match as string or parse as date and later format as string.
Given that $DateInDatabase = '2018-05-08 15:54:40' and $DateSpecific = '2018-05-08'
if (false !== strpos($DateInDatabase,$DateSpecific)) {
/* matched */
}
OR
$format = 'Ymd';
$DateInDatabase = (new DateTime($DateInDatabase))->format($format);
$DateSpecific = (new DateTime($DateSpecific))->format($format);
if ($DateInDatabase === $DateSpecific) {
/* matched */
}
This will check if your dates are equal. Be aware that PHP's date function has a limit in how far you can go for the year. The minimum is 01-01-1970 and the maximum is 19-01-2038 (d-m-Y format used here). The date is converted to an integer (strtotime). If those numbers are equal, the dates are equal.
$DateInDatabase = '2018-05-08 15:54:40'
$DateSpecific = '2018-05-08'
$newDate1 = date("Y-m-d", strtotime($DateInDatabase));
$newDate2 = date("Y-m-d", strtotime($DateSpecific));
if ($newDate1 == $newDate2) {
//equal
} else {
//not equal
}

Skip a value in do-while loop

I've got a script that sets up a array of dates which form a dropdown. The array is set up by some variables about the current date and an fixed offset for the last date (two weeks). Stripped down this is what it looks like:
public function getDatesOptionArray()
{
$datesArray = array();
$displayDate = Mage::getModel('core/locale')->storeDate();
$displayDate->add($this->_startDaysOffset, Zend_Date::DAY);
$dayOffset = $this->_startDaysOffset;
do
{
$dayofweek = date('w', strtotime($displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)));
$datesArray[$displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)] = Mage::helper('core')->formatDate($displayDate, Mage_Core_Model_Locale::FORMAT_TYPE_FULL);
$displayDate->add('1', Zend_Date::DAY);
$dayOffset++;
} while ($dayOffset <= $this->_endDaysOffset);
return $datesArray;
}
The thing is I want to leave out all the 'Sunday' options, and I've got the $dayofweek variable for each, where sunday is 0. I've tried to wrap the whole thing inside the do function in an if-statement (if $dayofweek !== 0), set an if ($dayofweek == 0) { continue;} and every other trick I could think of, but I get only either of these results
1: Only the first date is shown
2: All dates until the first sunday are shown, none after that
3: All dates are shown
I think I might be missing the point on the do-while loop; how do I exclude if $dayofweek == 0?
For me is something like this, i use while because Do...While(...) the first time it will not check your condition you'll enter your loop at last 1 time, and when you use while(...){} every time your program will check your condition
public function getDatesOptionArray()
{
$datesArray = array();
$displayDate = Mage::getModel('core/locale')->storeDate();
$displayDate->add($this->_startDaysOffset, Zend_Date::DAY);
$dayOffset = $this->_startDaysOffset;
while ($dayOffset <= $this->_endDaysOffset)
{
$dayofweek = date('w', strtotime($displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)));
if ($dayofweek != 0) {
$datesArray[$displayDate->toString(Varien_Date::DATE_INTERNAL_FORMAT)] = Mage::helper('core')->formatDate($displayDate, Mage_Core_Model_Locale::FORMAT_TYPE_FULL);
}
$displayDate->add('1', Zend_Date::DAY);
$dayOffset++;
}
return $datesArray;
}
Let say the array is
$date = array(
2017-10-12,
2017-10-13,
2017-10-14,
2017-10-15,
2017-10-16,
2017-10-17,
2017-10-18,
2017-10-19,
2017-10-20,
2017-10-21,
2017-10-22,
2017-10-23,
2017-10-24,
2017-10-25
);
Now do this for remove sunday's dates
$i=0;
do{
if(date('w',strtotime($date[$i]))>0) $dateArray[] = $date[$i];
$i++;
} while ($i<count($date));
echo "<pre>";print_r($dateArray);
return $datesArray;
$dateArray will give you dates without sundays.

Get the nearest date in the future

I would like to get the first date in the future from an array of dates. I've tried to write my own function, which did not get the job done.
private static function getClosestDate($date, array $dates, $last) {
$interval = array();
$now = strtotime(date('Y-m-d'));
foreach ($dates as $d) {
$dateTime = strtotime($date);
$toTime = strtotime($d);
// Do not parse dates older than today
if (strtotime($d) < $now) { continue 1; }
// Only do dates in the future
if ($toTime < $dateTime) { continue 1; }
$interval[] = abs($dateTime - $toTime);
}
// If there is no interval, use the latest date
if (!count($interval)) {
return $last;
}
asort($interval);
$closest = key($interval);
return $dates[$closest];
}
This code works but it also works the other way around. Next to that, when there is no last date, it should use the $last parameter which is the last date.
The reason I want to know this is because I have a range of dates on which people can book nights on. I want to know the difference in days to calculate the amount of nights they can book. Calculating a difference in dates is easy, but I do need to know when the next booking appears. These are provided in the $dates parameter.
What should I change in my code to get it fixed (I've tried to continue the foreach whenever the date was in the past based on the $date parameter) or can someone provide me the code?
I've fixed the problem myself. Instead of using the dates array I'm now using the date as key in the interval to retrieve the date again. This does work properly.
private static function getClosestDate($date, array $dates, $last) {
$interval = array();
$now = strtotime(date('Y-m-d'));
foreach ($dates as $d) {
$dateTime = strtotime($date);
$toTime = strtotime($d);
// Do not parse dates older than today
if (strtotime($d) < $now) { continue 1; }
// Only do dates in the future
if ($toTime < $dateTime) { continue 1; }
$interval[$d] = abs($dateTime - $toTime);
}
// If there is no interval, use the latest date
if (!count($interval)) {
return $last;
}
asort($interval);
$closest = key($interval);
return $closest;
}

Php dates is not compare properly

I am new in PHP
when I am trying to do this
if( date('m-Y',strtotime('2016-11-01 00:00:00')) < date('m-Y') ) {
echo "yes";
} else {
echo 'no';
}
but it always do false [output 'no'].
I must need to compare months is less than current month , means compare date do not have same months
where I am wrong to compare that date ?
Use DateTime to compare dates:
$date = new DateTime('2016-11-01 00:00:00');
$now = new DateTime();
if ($date < $now && $date->format('m-Y') != $now->format('m-Y')) {
echo 'yes';
} else {
echo 'no';
}
I copied your program so that it reads:
<?php
$x=date('m-Y',strtotime('2016-11-01 00:00:00'));
echo "$x\n";
$y=date("m-Y");
echo "$y\n";
if ($x < date('m-Y') ) {
echo "yes";
} else {
echo 'no';
}
On running it the output is:
# php x.php
11-2016
01-2017
no
That is why it fails. If you are checking for just the month you need to check for equality. Otherwise you need to reorder the date formatting to be "Y-m" (not 'm-Y') for less/greater than comparisons. Comparing the strings is fine.
date function always return a string. In your if construct you compare two strings. For current time:
"11-2016" < "01-2017"
In this case "11-2016" greater than "01-2017".
It will be better to use DateTime class.
$date = new DateTime('2016-11-01 00:00:00');
$now = new DateTime();
if ($date < $now && $date->format('m-Y') != $now->format('m-Y')) {
echo 'yes';
} else {
echo 'no';
}
or in your example you need to change format to 'Y-m'.
You should use a decent format to compare the dates. Instead of m-Y, use Y-m-d.
Currently, you are converting the dates to strings, with their months first. So the first date becomes 11-2016, the second becomes 01-2017. PHP compares these as strings, and finds that 0 is less thans 1, so considers the second string to be less.

Php custom date format and comparison

In my database I have one table in which I keep registered users.
One column is Date of register and I keep this value in my own string format.
For example "[2013-11-30] [19:42:46]"
Then I want to make a check.
If user is 30 days old or more.
The sure thing is that the above code is wrong.
The problem is that if one user registers at 29/01/2015
will not been showing in 30 last days if the current day is 02/02/2015!
//Datetime
$today = date_parse_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_parse_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if (
(($store[year] >= $today[year]) && ($store[month] >= $today[month]))
)
{ $date_last = "<font color='green'>".$row["LastSeen"]."</font>"; }
else
{ $date_last = "<font color='red'>".$row["LastSeen"]."</font>"; }
Use date_create_from_format instead of date_parse_from_format. Then you can simply compare the resulting values:
$today = date_create_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_create_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if ($store < $today) {
// ...
}
else {
// ...
}

Categories