My variable is not being filled, remains empty - php

I have a problem with comparing dates. I pull one date from a database through an API. These dates are stored in an array because one column contains multiple dates and I have to cycle through them to find the next upcoming date. The dates are in the format: 'dd/mm/yy'
$rawDate = $e->calendarsummary;
$filter = preg_replace("/[a-z]/","", $rawDate);
$createArray = explode(',', $filter);
$dates = array_filter(array_map('trim', $createArray));
foreach($dates as $d)
{
$dateTime = DateTime::createFromFormat('dmy', $d);
if($dateTime >= $now)
{
$finalDate = $dateTime;
$total = $finalDate->format('l j/m/y');
break;
}
}
If I place a var_export of $dateTime after $dateTime = DateTime::createFromFormat('dmy', $d); it returns 'false'. So I'm guessing $dateTime is empty although my array $dates is filled correctly.
a var_export of $dates returns:
array ( 0 => '15/06/13', 1 => '16/06/13', )
and a var export of $now returns todays date: '16/06/13'
So I'm a bit stuck why my variable $DateTime remains empty?
EDIT: Apparantly the return of 'false' means it's an error, so something went wrong when formatting my dates from the array?

If the $dates array contains elements such 15/06/13 so use just use wrong date format. E.g.:
$dateTime = DateTime::createFromFormat('d/m/y', $d);

$dateTime = DateTime::createFromFormat('d/m/y', $d);
not
$dateTime = DateTime::createFromFormat('dmy', $d);

Your dates are in format d/m/y, not dmy. Try the following instead:
$dateTime = DateTime::createFromFormat('d/m/y', $d);
When I do that, I get:
class DateTime#1 (3) { public $date => string(19) "2013-06-15 17:17:12" public $timezone_type => int(3) public $timezone => string(3) "UTC" }
... instead of bool(false).

you could use strtotime as a different method.
$now = date('d/m/y');
foreach($dates as $d)
{
if(strtotime($d) >= strtotime($now))
{
$finalDate = $dateTime;
$total = date('l j/m/y', strtotime($d));
break;
}
}

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

Display the item nearest to current time

I have a list of dates/times items in PHP array that are formatted like this:
2019-03-19 00:00:00
2019-03-19 02:30:00
2019-03-19 05:00:00
2019-03-19 14:30:00
2019-03-19 23:59:59
etc.
I'm sure this is easy, I just can't wrap my head around it. What equation do I use to display the item that is closest to the current time without going over.
So if current time is 22:00:00, I would want to display item 14:30:00, rather than 23:59:59.
Since your times are in Y-m-d H:i:s you can just compare them as strings and use a simple foreach loop to get your result:
$dates = array('2019-03-19 00:00:00',
'2019-03-19 02:30:00',
'2019-03-19 05:00:00',
'2019-03-19 14:30:00',
'2019-03-19 23:59:59');
$now = date('Y-m-d H:i:s');
$latest = '';
// add sort($dates) here if they are not already sorted.
foreach ($dates as $date) {
if ($date > $now) break;
$latest = $date;
}
echo $latest;
Demo on 3v4l.org
Note this code assumes your dates are already sorted, if not, add sort($dates) before the foreach loop.
First of all convert all the Dates to this format
$changed_date_1 = date('YmdHis', strtotime($orignaldate_1));
$changed_date_2 = date('YmdHis', strtotime($orignaldate_2));
$changed_date_3 = date('YmdHis', strtotime($orignaldate)_3);
so 2019-03-19 00:00:00 will become 20190319000000, and so on, now they can be compared easily.
than run a foreach loop in which iterate through all these date
$closestdate= date('Y-m-d H:i:s');//intaily set it to current date
$closest_difference= 99999999999999999;//intaily set a big value, more than 15 digits
foreach($datesArray as $item){
$difference = $item - date('YmdHis');
if($difference < $closest_difference){
$closes_difference = $difference;
$closestdate = $item;//this item is closest one. in next iteration this may change
}
}
echo $Closesdate;
/**
* Gets the nearest moment of the same day as $today.
*
* #param string[] $dates - A list of dates (needed format: "Y-m-d H:i:s")
* #param string|null $today - The date used for comparaison. (default is current date)
* #return string|bool - Returns the nearest date, or false.
*/
function getNearestDate(array $dates, ?string $today = null) {
if (!$today) {
$today = date('Y-m-d H:i:s');
}
$fnDT = function($d) {
return DateTime::createFromFormat('Y-m-d H:i:s', $d);
};
usort($dates, function($a, $b) use ($fnDT, $today) {
$da = abs($fnDT($today)->getTimestamp() - $fnDT($a)->getTimestamp());
$db = abs($fnDT($today)->getTimestamp() - $fnDT($b)->getTimestamp());
return $da - $db;
});
$nearest = $dates[0];
if ($fnDT($nearest)->format('Y-m-d') !== $fnDT($today)->format('Y-m-d')) {
print_r('No date of the same day.');
return false;
}
return $nearest;
}
Test it on 3v4l.org

Verifiying 2 date to make sure they're valid dates

I am working with a date which is formatted like so:
25/02/1994 - 15/03/2000
To get each date I am using the explode function to separate each date between dash
$newdate = explode("-",$olddate);
Now my problem is, if it was just one date I could split it up in to 3 parts, the day, month, year and use the checkdate function to validate the month, but because I am using explode I cannot split it up like that (to my knowledge)
What would be the best way to validate the date for legitimacy?
You have a good start, after you exploded your string by -, just simply loop through each date with array_reduce() and reduce it to 1 value.
In the anonymous function you just explode() each date and check with checkdate() if it is a valid date, e.g.
<?php
$str = "25/02/1994 - 15/03/2000";
$dates = explode("-", $str);
if(array_reduce($dates, function($keep, $date){
list($day, $month, $year) = array_map("trim",explode("/", $date));
if(!checkdate($month, $day, $year))
return $keep = FALSE;
return $keep;
}, TRUE)) {
echo "all valid dates";
}
?>
$date = '25/02/1994 - 15/03/2000';
$date_array = explode("-", $date);
$first_date = explode("/", trim($date_array[0]));
$second_date = explode("/", trim($date_array[1]));
if(checkdate($first_date[1],$first_date[0],$first_date[2])){
//do stuff
}
if(checkdate($second_date[1],$second_date[0],$second_date[2])){
//do stuff
}
or, what Daan suggested using the DateTime object.
$date = '25/02/1994 - 15/03/2000';
$date_array = explode("-", $date);
$date1 = DateTime::createFromFormat('j-M-Y', $date_array[0]);
$date2 = DateTime::createFromFormat('j-M-Y', $date_array[1]);
if($date1){
//do stuff
}
if($date2){
//do stuff
}

How to find date difference excluding specific dates in array - PHP

I know how to calculate date difference using PHP like;
$newdate = "01-03-2013";
$olddate = "01-06-2013";
$date_diff = abs(strtotime($olddate)-strtotime($newdate)) / 86400;
echo $date_diff;
But suppose, if I have some dates in an array like;
$datesarray = array(10-05-2013, 20-05-2013, 12-08-2013);
etc., holding some specific dates, is it possible to calculate date difference excluding the dates in array along with the Sundays, if they lie in between the start and end dates?
just loop through the $datesarray and check for each one if it's between the $olddate and $newdate. If so, increase a $counter variable (which starts at 0, obviously).
Then $date_diff - $counter will give you the expected result.
I would use the DateTime class in a custom function like this:
function dates_between(DateTime $start, DateTime $end, $format = 'm-d-Y') {
$date = $start;
$dates = array();
$oneDay = new DateInterval('P1D');
// push all dates between start and end to the result
while(($date = $date->add($oneDay)) < $end) {
$dates []= $date->format($format);
}
return $dates;
}
Example usage:
$now = new DateTime();
$nextWeek = new DateTime('+1 week');
var_dump(dates_between($now, $nextWeek));
Output:
array(6) {
[0] =>
string(10) "07-12-2013"
[1] =>
string(10) "07-13-2013"
[2] =>
string(10) "07-14-2013"
[3] =>
string(10) "07-15-2013"
[4] =>
string(10) "07-16-2013"
[5] =>
string(10) "07-17-2013"
}
The following script creates and array of timestamps from your array of UK dates and then calculates the max and min timestamps to calculate the days difference.
If the timestamp defaults to 0, it is not added to the timestamp array, avoiding huge results for one bad date defaulting to the epoch
I.e. When date is invalid or pre epoch 1/1/1970
<?php
$datesarray = array('10-05-2013', '20-05-2013', '12-08-2013');
$date_diff=0; // default for 0 or 1 dates
if( (is_array($datesarray)) && (sizeof($datesarray)>1) )
{
$timestampsarray=array();
reset($datesarray);
while(list($key,$value)=each($datesarray))
{
$timestamp=timestamp_from_UK($value);
if($timestamp!=0) $timestampsarray[$key]=$timestamp;
}
$date_diff = abs(max($timestampsarray)-min($timestampsarray)) / 86400;
}
echo $date_diff;
function timestamp_from_UK($ukdatetime)
{
// where PHP is processing UK dates d-m-y correctly
$ukdatetime=str_replace('/', '-', $ukdatetime);
if(date("d", strtotime("1-2-1970"))==1) return strtotime($ukdatetime);
// Fallback script for when PHP is NOT processing UK dates
$success=false;
if(!$success) $success=preg_match("/([0-9]{1,2})[^0-9]([0-9]{1,2})[^0-9]([0-9]{2,4})[^0-9]([0-9]{1,2})[^0-9]([0-9]{1,2})[^0-9]([0-9]{1,2})/", $ukdatetime, $matches);
if(!$success) $success=preg_match("/([0-9]{1,2})[^0-9]([0-9]{1,2})[^0-9]([0-9]{2,4})[^0-9]([0-9]{1,2})[^0-9]([0-9]{1,2})/", $ukdatetime, $matches);
if(!$success) $success=preg_match("/([0-9]{1,2})[^0-9]([0-9]{1,2})[^0-9]([0-9]{2,4})/", $ukdatetime, $matches);
if(!$success) return 0;
// ensure all values are set - to avoid invalid offset
for($i=4;$i<=6;$i++)
{
if(!isset($matches[$i])) $matches[$i]=0;
}
// $matches[0] is the full matched string
return mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[1], $matches[3]);
}
?>

Add missing dates to an array

I have the following array:
Array ( [2010-10-30] => 1 [2010-11-11] => 1 [2010-11-13] => 11 )
I am trying to fill in the array with all the missing dates between the first and last elements. I was attempting using the following but got nowhere:
foreach($users_by_date as $key => $value){
$real_next_day = date($key, time()+86400);
$array_next_day = key(next($users_by_date));
if($real_next_day != $array_next_day){
$users_by_date[$real_next_day] = $value;
}
}
The DateTime, DateInterval and DatePeriod classes can really help out here.
$begin=date_create('2010-10-30');
$end=date_create('2010-11-13');
$i = new DateInterval('P1D');
$period=new DatePeriod($begin,$i,$end);
foreach ($period as $d){
$day=$d->format('Y-m-d');
$usercount= isset($users_by_date[$day]) ? $users_by_date[$day] :0;
echo "$day $usercount";
}
I have been waiting for a chance to try out DateTime and DateInterval objects in PHP 5.3, your question was the perfect opportunity to do just that. Note that this code will not work with PHP versions earlier than 5.3
<?php
$dates = array('2010-10-30' => 1, '2010-11-01' => 1, '2010-11-13' => 1);
// get start and end out of array
reset($dates);
$start = new DateTime(key($dates));
end($dates);
$end = new DateTime(key($dates));
foreach (new DatePeriod($start, new DateInterval('P1D'), $end) as $date) {
$dateKey = $date->format('Y-m-d'); // get properly formatted date out of DateTime object
if (!isset($dates[$dateKey])) {
$dates[$dateKey] = 1;
}
}
print_r($dates);
The functions you are looking for (but not using in your example) are strtotime & diff
You would get the day range between your two dates $numdiff, and simply do something in a loop that would do:
for ($i=1; $i<=$numdiff; $i++) {
echo date("Y-m-d", strtotime("2010-10-30 +".$i." day"));
}
Result should be something like:
2010-10-31
2010-11-01
2010-11-02...
You could then pop that into your array as needed. Hope that gets you started in the right direction.
For indexes using timestamps, you can generate your array easily using the range function.
$startStamp = ...
$endStamp = ...
$oneDay = 60*60*24;
$timeIndexes = range($startStamp, $endStamp, $oneDay);
$filler = array_fill(0, count($timeIndexes), null);
$timeArray = array_combine($timeIndexes, $filler);
I am not sure what values you want in the array, but hopefully it is relatively straight-forward from here.
If you are going to be converting every timestamp to a formatted date string anyhow and would just prefer to use date strings in the first place, consider this modification.
$dateStringIndexes = array_map(
function ($t) {
return date('Y-m-d', $t);
},
$timeIndexes
);
Of course, since you are on PHP 5.2, you will likely have to compromise with a foreach loop instead of the closure.
This is the PHP 5.2 capable function I came up with that works.
Thanks guys
reset($users_by_date);
$date = key($users_by_date);
end($users_by_date);
$end = key($users_by_date);
while(strtotime($date) <= strtotime($end)){
$datearray[] = date("Y-m-d", strtotime($date));
$date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
}
foreach($datearray as $key => $value){
if(!isset($users_by_date[$value])){
$users_by_date[$value] = 0;
}
}
ksort($users_by_date);

Categories