A non well formed numeric value encountered in ...on Line 171 - php

We keep getting the above error. Have tried adding a $start above 171 but same result. Here is the code :
/**
* Get all of the months since a certain date
*/
public static function getMonthsSinceDate($start) {
$key_month = date('MY', $start); (note this is Line 171)
$key = 'months_since_' . $key_month;
$months = CodonCache::read($key);
if ($months === false) {
if (!is_numeric($start)) {
$start = strtotime($start);
}
$end = date('Ym');
do {
# Get the months
$month = date('M Y', $start);
$months[$month] = $start; # Set the timestamp
$start = strtotime('+1 month +1 day', strtotime($month));
# Convert to YYYYMM to compare
$check = intval(date('Ym', $start));
} while ($check <= $end);
CodonCache::write($key, $months, 'long');
}
return $months;
}
/**

Wherever you are calling the function getMonthsSinceDate(); you are accidentally passing it something non numeric. It could be subtle like a number wrapped in quotes which would become a string, i.e
getMonthsSinceDate('111111')

PHP's date() expects to be given a date in an integer UNIX timestamp. If you are trying to pass a human-readable date as a string it will throw an error.
If you are, convert it to a timestamp using strtotime(), like this:
$start = strtotime( $start );

Related

PHP giving fatal error on comparing dates

I have one date in database, and I want to compare it with the current date. So I write the following function:
$today = new DateTime();
$today_date = $current_date->format('Y-m-d H:i:s');
function do_diifernce($date_1, $date_2) {
$my_date = $date_1;
$createDate = new DateTime($my_date);
$strip = $createDate->format('Y-m-d');
$difference = $date_2->diff($createDate, true);
$difference->total_difference = $difference->y . "." . $difference->m;
return $difference;
}
$comparison = do_diifernce($databse_date, $today_date);
So
$databse_date = 2019-06-01 00:00:00.000000
$today_date = 2019-05-06 10:48:01
But I can't print the value of $comparison.
PHP Fatal error: Uncaught Error: Call to a member function diff() on string
How can I solve it?
You pass in $today_date to do_diifernce(), which is a string (as you have formatted it with format()). You can either pass $today in (which is an object), or include a condition that checks if its an object or not.
function do_difference($date_1, $date_2) {
// Check if the arguments were DateTime objects - if not, instantiate them as that
if (!($date_1 instanceof DateTime)) {
$date_1 = new DateTime($date_1);
}
if (!($date_2 instanceof DateTime)) {
$date_2 = new DateTime($date_2);
}
// Compare the difference and return the Y and m properties
$difference = $date_2->diff($date_1);
$difference->total = $difference->y . "." . $difference->m;
return $difference;
}
$today = new DateTime();
$comparison = do_difference($databse_date, $today);
You were playing date 2 as string which should be treated as datetime object to get the difference between two datetime objects.
function do_diifernce($date_1, $date_2)
{
$createDate1 = new DateTime($date_1);
$createDate2 = new DateTime($date_2);
$difference = $createDate2->diff($createDate1);
$sign = ($createDate1 < $createDate2 ? '-':'+');
$difference->total_difference = $difference->format("%r%a");
return $difference;
}
$databse_date = "2019-05-01 00:00:00";
$today_date = "2019-05-06 10:48:01";
$comparison = do_diifernce($databse_date, $today_date);
print_r($comparison);die;
Here is official doc.
You check that array as there is no difference of year and month as both dates belongs to same month and year so its coming 0.0
You got an error here: $difference = $date_2->diff($createDate, true);. AFAIK, the diff() function is deprecated after PHP 5.3.
If you want to calculate the difference between two dates, you can use date_diff as follows.
<?php
$date1 = date_create("2000-04-01");
$date2 = date_create("2019-04-06");
$diff = date_diff($date1, $date2);
?>
It throws an error, because you call format on date2, which returns a string, no DateTime object.
Remove the call to format, then your comparison should work.
All you have to do, is to replace the last line with the following:
$comparison=do_diifernce($databse_date, $today);

how to get Random date between 2 date values using php? [duplicate]

I am coding an application where i need to assign random date between two fixed timestamps
how i can achieve this using php i've searched first but only found the answer for Java not php
for example :
$string = randomdate(1262055681,1262055681);
PHP has the rand() function:
$int= rand(1262055681,1262055681);
It also has mt_rand(), which is generally purported to have better randomness in the results:
$int= mt_rand(1262055681,1262055681);
To turn a timestamp into a string, you can use date(), ie:
$string = date("Y-m-d H:i:s",$int);
If given dates are in date time format then use this easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.
A quick PHP example would be:
// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
// Convert to timetamps
$min = strtotime($start_date);
$max = strtotime($end_date);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}
This function makes use of strtotime() as suggested by zombat to convert a datetime description into a Unix timestamp, and date() to make a valid date out of the random timestamp which has been generated.
Another solution using PHP DateTime
$start and $end are DateTime objects and we convert into Timestamp. Then we use mt_rand method to get a random Timestamp between them. Finally we recreate a DateTime object.
function randomDateInRange(DateTime $start, DateTime $end) {
$randomTimestamp = mt_rand($start->getTimestamp(), $end->getTimestamp());
$randomDate = new DateTime();
$randomDate->setTimestamp($randomTimestamp);
return $randomDate;
}
You can just use a random number to determine a random date. Get a random number between 0 and number of days between the dates. Then just add that number to the first date.
For example, to get a date a random numbers days between now and 30 days out.
echo date('Y-m-d', strtotime( '+'.mt_rand(0,30).' days'));
Here's another example:
$datestart = strtotime('2009-12-10');//you can change it to your timestamp;
$dateend = strtotime('2009-12-31');//you can change it to your timestamp;
$daystep = 86400;
$datebetween = abs(($dateend - $datestart) / $daystep);
$randomday = rand(0, $datebetween);
echo "\$randomday: $randomday\n";
echo date("Y-m-d", $datestart + ($randomday * $daystep)) . "\n";
The best way :
$timestamp = rand( strtotime("Jan 01 2015"), strtotime("Nov 01 2016") );
$random_Date = date("d.m.Y", $timestamp );
By using carbon and php rand between two dates
$startDate = Carbon::now();
$endDate = Carbon::now()->subDays(7);
$randomDate = Carbon::createFromTimestamp(rand($endDate->timestamp, $startDate->timestamp))->format('Y-m-d');
OR
$randomDate = Carbon::now()->subDays(rand(0, 7))->format('Y-m-d');
An other solution where we can use date_format :
/**
* Method to generate random date between two dates
* #param $sStartDate
* #param $sEndDate
* #param string $sFormat
* #return bool|string
*/
function randomDate($sStartDate, $sEndDate, $sFormat = 'Y-m-d H:i:s') {
// Convert the supplied date to timestamp
$fMin = strtotime($sStartDate);
$fMax = strtotime($sEndDate);
// Generate a random number from the start and end dates
$fVal = mt_rand($fMin, $fMax);
// Convert back to the specified date format
return date($sFormat, $fVal);
}
Source : https://gist.github.com/samcrosoft/6550473
You could use for example :
$date_random = randomDate('2018-07-09 00:00:00','2018-08-27 00:00:00');
The amount of strtotime in here is WAY too high.
For anyone whose interests span before 1971 and after 2038, here's a modern, flexible solution:
function random_date_in_range( $date1, $date2 ){
if (!is_a($date1, 'DateTime')) {
$date1 = new DateTime( (ctype_digit((string)$date1) ? '#' : '') . $date1);
$date2 = new DateTime( (ctype_digit((string)$date2) ? '#' : '') . $date2);
}
$random_u = random_int($date1->format('U'), $date2->format('U'));
$random_date = new DateTime();
$random_date->setTimestamp($random_u);
return $random_date->format('Y-m-d') .'<br>';
}
Call it any number of ways ...
// timestamps
echo random_date_in_range(157766400,1489686923);
// any date string
echo random_date_in_range('1492-01-01','2050-01-01');
// English textual parsing
echo random_date_in_range('last Sunday','now');
// DateTime object
$date1 = new DateTime('1000 years ago');
$date2 = new DateTime('now + 10 months');
echo random_date_in_range($date1, $date2);
As is, the function requires date1 <= date2.
i had a same situation before and none of the above answers fix my problem so i
Came with new function
function randomDate($startDate, $endDate, $count = 1 ,$dateFormat = 'Y-m-d H:i:s')
{
//inspired by
// https://gist.github.com/samcrosoft/6550473
// Convert the supplied date to timestamp
$minDateString = strtotime($startDate);
$maxDateString = strtotime($endDate);
if ($minDateString > $maxDateString)
{
throw new Exception("From Date must be lesser than to date", 1);
}
for ($ctrlVarb = 1; $ctrlVarb <= $count; $ctrlVarb++)
{
$randomDate[] = mt_rand($minDateString, $maxDateString);
}
if (sizeof($randomDate) == 1)
{
$randomDate = date($dateFormat, $randomDate[0]);
return $randomDate;
}elseif (sizeof($randomDate) > 1)
{
foreach ($randomDate as $randomDateKey => $randomDateValue)
{
$randomDatearray[] = date($dateFormat, $randomDateValue);
}
//return $randomDatearray;
return array_values(array_unique($randomDatearray));
}
}
Now the testing Part(Data may change while testing )
$fromDate = '2012-04-02';
$toDate = '2018-07-02';
print_r(randomDate($fromDate,$toDate,1));
result will be
2016-01-25 11:43:22
print_r(randomDate($fromDate,$toDate,1));
array:10 [▼
0 => "2015-08-24 18:38:26"
1 => "2018-01-13 21:12:59"
2 => "2018-06-22 00:18:40"
3 => "2016-09-14 02:38:04"
4 => "2016-03-29 17:51:30"
5 => "2018-03-30 07:28:48"
6 => "2018-06-13 17:57:47"
7 => "2017-09-24 16:00:40"
8 => "2016-12-29 17:32:33"
9 => "2013-09-05 02:56:14"
]
But after the few tests i was thinking about what if the inputs be like
$fromDate ='2018-07-02 09:20:39';
$toDate = '2018-07-02 10:20:39';
So the duplicates may occur while generating the large number of dates such as 10,000
so i have added array_unique and this will return only the non duplicates
if you use laravel then it's for you.
\Carbon\Carbon::now()->subDays(rand(0, 90))->format('Y-m-d');
Simplest of all, this small function works for me
I wrote it in a helper class datetime as a static method
/**
* Return date between two dates
*
* #param String $startDate
* #param String $endDate
* #return String
*
* #author Kuldeep Dangi <kuldeepamy#gmail.com>
*/
public static function getRandomDateTime($startDate, $endDate)
{
$randomTime = mt_rand(strtotime($startDate), strtotime($endDate));
return date(self::DATETIME_FORMAT_MYSQL, $randomTime);
}
Pretty good question; needed to generate some random sample data for an app.
You could use the following function with optional arguments to generate random dates:
function randomDate($startDate, $endDate, $format = "Y-M-d H:i:s", $timezone = "gmt", $mode = "debug")
{
return $result;
}
sample input:
echo 'UTC: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", "utc") . '<br>';
//1942-Jan-19 07:00:00
echo 'GMT: ' . randomDate("1942-01-19", "2016-06-03", "Y/M/d H:i A", "gmt") . '<br>';
//1942/Jan/19 00:00 AM
echo 'France: ' . randomDate("1942-01-19", "2016-06-03", "Y F", "Europe/Paris") . '<br>';
//1942 January
echo 'UTC - 4 offset time only: ' . randomDate("1942-01-19", "2016-06-03", "H:i:s", -4) . '<br>';
//20:00:00
echo 'GMT +2 offset: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", 2) . '<br>';
//1942-Jan-19 02:00:00
echo 'No Options: ' . randomDate("1942-01-19", "2016-06-03") . '<br>';
//1942-Jan-19 00:00:00
readers requirements could vary from app to another, in general hope this function is a handy tool where you need to generate some random dates/ sample data for your application.
Please note that the function initially in debug mode, so change it to $mood="" other than debug in production .
The function accepts:
start date
end date
format: any php accepted format for date or time
timezone: name or offset number
mode: debug, epoch, verbose epoch or verbose
the output in not debug mode is random number according to optional specifications.
tested with PHP 7.x
// Find a randomDate between $startDate and $endDate
function randomDate($startDate, $endDate)
{
// Convert to timetamps
$min = strtotime($startDate);
$max = strtotime($endDate);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to date
return Carbon::createFromTimestamp($val);
}
dd($this->randomDate('2014-12-10', Carbon::now()->toString()));
Using carbon
$yeni_tarih = date('Y-m-d', strtotime( '+'.mt_rand(-90,0).' days'))." ".date('H', strtotime( '+'.mt_rand(0,24).' hours')).":".rand(1,59).":".rand(1,59);
Full random date and time

Calculating percent of time remaining from two dates

So far im trying to get the percentage of time remaining between two dates so i can use a progress bar..
I have the following code i'm passing in two dates and doing the sum but i am getting an error. i'm not sure if this error is because of the date format if so i can change it.
<?
$start = '2015-11-03 14:05:15';
$end = '2015-11-03 18:05:15';
$current = '2015-11-03 16:12:15';
$completed = (($current - $start) / ($end - $start)) * 100;
?>
<? print $completed; ?>
I am getting the following error.
Warning: Division by zero
strtotime will take a date string and turn it into unix standard time as seconds.
<?
$start = strtotime('2015-11-03 14:05:15');
$end = strtotime('2015-11-03 18:05:15');
$current = strtotime('2015-11-03 16:12:15');
$completed = (($current - $start) / ($end - $start)) * 100;
?>
<? print $completed; ?>
I would recommend using the DateTime object over strtotime. DateTime allows you to specify the format that creates the timestamp, instead of relying on strtotime to magically figure it out. This makes it far more reliable.
For example:
<?php
$start = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 14:05:15');
$end = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 18:05:15');
$current = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 16:12:15');
$completed = (($current->getTimestamp() - $start->getTimestamp()) / ($end->getTimestamp() - $start->getTimestamp())) * 100;
echo $completed;
?>
Note: DateTime objects were introduced in PHP 5.3. Any older versions will not have DateTime. (and quite honestly, should be updated for many reasons)
You're using strings (basically, plain text)... So you can't calculate anything.
You should use timestamps for that (miliseconds since start of 1970)
http://php.net/manual/fr/function.strtotime.php
$start = strtotime('2015-11-03 14:05:15');
$end = strtotime('2015-11-03 18:05:15');
$current = strtotime('2015-11-03 16:12:15');
Those are strings. You can't subtract strings and expect things to work. What's happening is this:
$start = '2015-11-03 14:05:15';
$end = '2015-11-03 18:05:15';
Since you're doing -, PHP converts those strings to integers:
$new_start = (int)$start; // 2015
$new_end = (int)$end; // 2015
$new_end - $new_start -> 0
YOu need to strtotime() those values back into a unix timestamp, and then you CAN subtract those values, and get a difference in seconds.

PHP strtotime +1 month behaviour

I know about the unwanted behaviour of PHP's function
strtotime
For example, when adding a month (+1 month) to dates like: 31.01.2011 -> 03.03.2011
I know it's not officially a PHP bug, and that this solution has some arguments behind it, but at least for me, this behavior has caused a lot waste of time (in the past and present) and I personally hate it.
What I found even stranger is that for example in:
MySQL: DATE_ADD('2011-01-31', INTERVAL 1 MONTH) returns 2011-02-28
or
C# where new DateTime(2011, 01, 31).AddMonths(1); will return 28.02.2011
wolframalpha.com giving 31.01.2013 + 1 month as input; will return Thursday, February 28, 2013
It sees to me that others have found a more decent solution to the stupid question that I saw alot in PHP bug reports "what day will it be, if I say we meet in a month from now" or something like that. The answer is: if 31 does not exists in next month, get me the last day of that month, but please stick to next month.
So MY QUESTION IS: is there a PHP function (written by somebody) that resolves this not officially recognized bug? As I don't think I am the only one who wants another behavior when adding / subtracting months.
I am particulary interested in solutions what also work not just for the end of the month, but a complete replacement of strtotime. Also the case strotime +n months should be also dealt with.
Happy coding!
what you need is to tell PHP to be smarter
$the_date = strtotime('31.01.2011');
echo date('r', strtotime('last day of next month', $the_date));
$the_date = strtotime('31.03.2011');
echo date('r', strtotime('last day of next month', $the_date));
assuming you are only interesting on the last day of next month
reference - http://www.php.net/manual/en/datetime.formats.relative.php
PHP devs surely don't consider this as bug. But in strtotime's docs there are few comments with solutions for your problem (look for 28th Feb examples ;)), i.e. this one extending DateTime class:
<?php
// this will give us 2010-02-28 ()
echo PHPDateTime::DateNextMonth(strftime('%F', strtotime("2010-01-31 00:00:00")), 31);
?>
Class PHPDateTime:
<?php
/**
* IA FrameWork
* #package: Classes & Object Oriented Programming
* #subpackage: Date & Time Manipulation
* #author: ItsAsh <ash at itsash dot co dot uk>
*/
final class PHPDateTime extends DateTime {
// Public Methods
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Calculate time difference between two dates
* ...
*/
public static function TimeDifference($date1, $date2)
$date1 = is_int($date1) ? $date1 : strtotime($date1);
$date2 = is_int($date2) ? $date2 : strtotime($date2);
if (($date1 !== false) && ($date2 !== false)) {
if ($date2 >= $date1) {
$diff = ($date2 - $date1);
if ($days = intval((floor($diff / 86400))))
$diff %= 86400;
if ($hours = intval((floor($diff / 3600))))
$diff %= 3600;
if ($minutes = intval((floor($diff / 60))))
$diff %= 60;
return array($days, $hours, $minutes, intval($diff));
}
}
return false;
}
/**
* Formatted time difference between two dates
*
* ...
*/
public static function StringTimeDifference($date1, $date2) {
$i = array();
list($d, $h, $m, $s) = (array) self::TimeDifference($date1, $date2);
if ($d > 0)
$i[] = sprintf('%d Days', $d);
if ($h > 0)
$i[] = sprintf('%d Hours', $h);
if (($d == 0) && ($m > 0))
$i[] = sprintf('%d Minutes', $m);
if (($h == 0) && ($s > 0))
$i[] = sprintf('%d Seconds', $s);
return count($i) ? implode(' ', $i) : 'Just Now';
}
/**
* Calculate the date next month
*
* ...
*/
public static function DateNextMonth($now, $date = 0) {
$mdate = array(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
list($y, $m, $d) = explode('-', (is_int($now) ? strftime('%F', $now) : $now));
if ($date)
$d = $date;
if (++$m == 2)
$d = (($y % 4) === 0) ? (($d <= 29) ? $d : 29) : (($d <= 28) ? $d : 28);
else
$d = ($d <= $mdate[$m]) ? $d : $mdate[$m];
return strftime('%F', mktime(0, 0, 0, $m, $d, $y));
}
}
?>
Here's the algorithm you can use. It should be simple enough to implement yourself.
Have the original date and the +1 month date in variables
Extract the month part of both variables
If the difference is greater than 1 month (or if the original is December and the other is not January) change the latter variable to the last day of the next month. You can use for example t in date() to get the last day: date( 't.m.Y' )
Had the same issue recently and ended up writing a class that handles adding/subtracting various time intervals to DateTime objects.
Here's the code:
https://gist.github.com/pavlepredic/6220041#file-gistfile1-php
I've been using this class for a while and it seems to work fine, but I'm really interested in some peer review. What you do is create a TimeInterval object (in your case, you would specify 1 month as the interval) and then call addToDate() method, making sure you set $preventMonthOverflow argument to true. The code will make sure that the resulting date does not overflow into next month.
Sample usage:
$int = new TimeInterval(1, TimeInterval::MONTH);
$date = date_create('2013-01-31');
$future = $int->addToDate($date, true);
echo $future->format('Y-m-d');
Resulting date is:
2013-02-28
Here is an implementation of an improved version of Juhana's answer above:
<?php
function sameDateNextMonth(DateTime $createdDate, DateTime $currentDate) {
$addMon = clone $currentDate;
$addMon->add(new DateInterval("P1M"));
$nextMon = clone $currentDate;
$nextMon->modify("last day of next month");
if ($addMon->format("n") == $nextMon->format("n")) {
$recurDay = $createdDate->format("j");
$daysInMon = $addMon->format("t");
$currentDay = $currentDate->format("j");
if ($recurDay > $currentDay && $recurDay <= $daysInMon) {
$addMon->setDate($addMon->format("Y"), $addMon->format("n"), $recurDay);
}
return $addMon;
} else {
return $nextMon;
}
}
This version takes $createdDate under the presumption that you are dealing with a recurring monthly period, such as a subscription, that started on a specific date, such as the 31st. It always takes $createdDate so late "recurs on" dates won't shift to lower values as they are pushed forward thru lesser-valued months (e.g., so all 29th, 30th or 31st recur dates won't eventually get stuck on the 28th after passing thru a non-leap-year February).
Here is some driver code to test the algorithm:
$createdDate = new DateTime("2015-03-31");
echo "created date = " . $createdDate->format("Y-m-d") . PHP_EOL;
$next = sameDateNextMonth($createdDate, $createdDate);
echo " next date = " . $next->format("Y-m-d") . PHP_EOL;
foreach(range(1, 12) as $i) {
$next = sameDateNextMonth($createdDate, $next);
echo " next date = " . $next->format("Y-m-d") . PHP_EOL;
}
Which outputs:
created date = 2015-03-31
next date = 2015-04-30
next date = 2015-05-31
next date = 2015-06-30
next date = 2015-07-31
next date = 2015-08-31
next date = 2015-09-30
next date = 2015-10-31
next date = 2015-11-30
next date = 2015-12-31
next date = 2016-01-31
next date = 2016-02-29
next date = 2016-03-31
next date = 2016-04-30
I have solved it by this way:
$startDate = date("Y-m-d");
$month = date("m",strtotime($startDate));
$nextmonth = date("m",strtotime("$startDate +1 month"));
if((($nextmonth-$month) > 1) || ($month == 12 && $nextmonth != 1))
{
$nextDate = date( 't.m.Y',strtotime("$initialDate +1 week"));
}else
{
$nextDate = date("Y-m-d",strtotime("$initialDate +1 month"));
}
echo $nextDate;
Somewhat similar to the Juhana's answer but more intuitive and less complications expected. Idea is like this:
Store original date and the +n month(s) date in variables
Extract the day part of both variables
If days do not match, subtract number of days from the future date
Plus side of this solution is that works for any date (not just the border dates) and it also works for subtracting months (by putting - instead of +).
Here is an example implementation:
$start = mktime(0,0,0,1,31,2015);
for ($contract = 0; $contract < 12; $contract++) {
$end = strtotime('+ ' . $contract . ' months', $start);
if (date('d', $start) != date('d', $end)) {
$end = strtotime('- ' . date('d', $end) . ' days', $end);
}
echo date('d-m-Y', $end) . '|';
}
And the output is following:
31-01-2015|28-02-2015|31-03-2015|30-04-2015|31-05-2015|30-06-2015|31-07-2015|31-08-2015|30-09-2015|31-10-2015|30-11-2015|31-12-2015|
function ldom($m,$y){
//return tha last date of a given month based on the month and the year
//(factors in leap years)
$first_day= strtotime (date($m.'/1/'.$y));
$next_month = date('m',strtotime ( '+32 day' , $first_day)) ;
$last_day= strtotime ( '-1 day' , strtotime (date($next_month.'/1/'.$y)) ) ;
return $last_day;
}

PHP Dates: Syntax Debug on PHP if conditional

In the following code $start is a start date manually entered into a datepicker and $end is a separate key also, entered via datepicker. These are being compared against date('ymd'), which is today.
Early in the code for this plugin we have this code (where the same argument returns true):
//Parse End Date
if($end):
$end = explode('-', $end);
$end = mktime($hour, $_POST['_date_minute'], 0, $end[0], $end[1], $end[2]);
if ((date('ymd',$start) < date('ymd',$end)) && (date('ymd',$end) >= date('ymd'))) {
$compare = date('ymd'); //Overwrite start date $compare
}
else {
$compare = date('ymd', $start);
}
endif;
Later in the code, the same argument returns false here:
function event_list_date($start_or_end, $format, $echo = true){
global $post;
// Check the end date, if it's greater than today and then start date is less than or equal to today, round it off so that it's today and doesn't look like the event is already past
// Original Code
// if ((date('ymd',$start) < date('ymd',$end)) && (date('ymd',$end) >= time('ymd'))) {
// Stackoverflow Proposed Change
// if ($start < $end && $end >= time('ymd')) {
if ($start < $end && $end >= time('ymd')) {
$start = date('ymd'); //Overwrite start date $compare
}
else {
$start = get_post_meta($post->ID, '_date_start', true);;
}
$end = get_post_meta($post->ID, '_date_end', true);
if($start_or_end == 'start'):
$date = date($format, $start);
if($echo): echo $date; else: return $date; endif;
elseif($start_or_end == 'end'):
$date = date($format, $end);
if($echo): echo $date; else: return $date; endif;
endif;
}
Can someone tell me why the if statement is returning false for an event with a $start value equal to yesterday and an $end equal to 5 days from now?
EDIT: Posting a "zoomed out" context of this code
The date function changes these into strings. Then you're using mathematical comparison operators to compare the strings, which does not work in the way you're wanting. If you want to compare a date against another date, you'll want to convert them to something more easily compared, like numbers.
strtotime will take care of that! Since you're passing $start into date() (which requires a numeric argument), I assume $start is already a numeric time representation. So, to compare against right now, use time();
strtotime docs
date docs

Categories