PHP Comparing Current Date to a Given Date - php

I am having a hard time getting a simple date check to work properly. I searched all the questions, and so far none of the solutions have helped me.
I want to do a loop from a certain date, until today.
What is currently happening with the below code is that its not stopping and just keeps going. When I log i, I can see the date is increasing by a day like it should. I also tried flipping the operator to <, but that caused the loop to be skipped entirely.
Any ideas?
$startOfPlayoffs = new DateTime( "2016-04-29" );
$today = date("Y-m-d");
for($i = $startOfPlayoffs; $i >= $today; $i->modify('+1 day'))
{
//... some stuff
}
Interestingly, when I hard-code the date, it works fine. I.E:
$endOfPlayoffs = new DateTime( "2016-05-02" );
That isn't ideal, so was hoping to get it to work properly.

You are comparing a PHP Date object ($startOfPlayoffs) with a string ($today). Try converting $today into a Date object:
$startOfPlayoffs = new DateTime("2016-04-29");
$today = new DateTime();
$cpt = 0;
for($i = $startOfPlayoffs; $i <= $today; $i->modify('+1 day')){
echo time($i) . "<br>";
if ($cpt++ >= 100) exit;// as a safeguard
}

use unix time stamps, they are concrete numbers that are much easier to deal with.
int time(void) //current time stamp
You can also use strtotime() to convert date strings into time stamps. See this question for conversion from numbered date formats to unix timestamps.

Use the ->diff() method of the DateTime class like this is quite clean
The ->diff() method produces an DateInterval Object that looks like this
DateInterval Object
(
[y] => 0
[m] => 3
[d] => 4
[h] => 17
[i] => 23
[s] => 4
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 95
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
So the code can be as simple as this
<?php
$startOfPlayoffs = new DateTime( "2016-01-29" );
$today= new DateTime();
$diff = $startOfPlayoffs ->diff($today);
for ( $i = 0; $i<$diff->days; $i++ ) {
// do stuff
}

use: date_format($startOfPlayoffs,"Y-m-d") to obtain a "variable" you can compare against...
$startOfPlayoffs = new DateTime( "2016-04-29" );
$today = date("Y-m-d");
for($i = date_format($startOfPlayoffs,"Y-m-d"); $i >= $today; $i->modify('+1 day'))
{
//... some stuff
}

Related

String timestamp to int, make a DateTime with it afterwards in PHP

I want to know if a timestamp stored in my database as a bigint (I'm using mariaDB) is already old comparing it to the current date, there's one example:
I have this timestamp stored in my db = 1560499685530 but for some reason, it is a string when I fetch it from my db so I got this error when trying to set its timestamp (setTimestamp($timestamp))
DateTime::setTimestamp() expects parameter 1 to be integer, string
given
I tried using intval but my timestamp seems to be too long to be int because when I use inval it returns another int, smaller than mine, I guess that's the PHP int cap
I want my PHP to print if it's already an old date comparing it to the current date and wrote this code
$qBloqueo = mysqli_query($conn, "SELECT * FROM dates WHERE idUsuario = '$idUsuario'") or die(mysqli_error($conn));
$timestamp = mysqli_fetch_assoc($qBloqueo);
$timestamp = intval($timestamp['timestamp']); // Getting the timestamp from my db which is a string, still dunno why, in my db it's a bigint
$today = new DateTime();
$expireDate = new DateTime();
$expireDate->setTimestamp($timestamp);
if($today->format("Y-m-d") > $expireDate->format("Y-m-d")) {
print('Old date ^u^');
} else {
print('Not yet');
}
How can I use a timestamp to make a date obj without been a int or there is any way to convert it from a string to int? I just want to make a date from a string timestamp so I could compare it to the current date
If only type is concern then you can type cast variable like:
$timestamp = (int) $timestamp['timestamp'];
If you're looking for difference between two times
<?php
$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');
?>
Output :
1 second(s)
Now to find difference between two timestamps
/* PHP/5.5.8 and later */
$start = new DateTimeImmutable('2016-04-20 00:37:15');
$end = $start->modify('+7 days');
$diff = $end->diff($start);
print_r($diff);
Output :
DateInterval Object ( [y] => 0 [m] => 0 [d] => 7 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 1 [days] => 7 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
To convert date timestamp into millisecond
$yourdate = '2016-03-22 14:30';
$stamp = strtotime($yourdate); // get unix timestamp
$time_in_ms = $stamp*1000;
print_r($time_in_ms);
Output :
1458657000000
You can convert both times into millisecond and find which one is greater.
I hope this helps in some way

Show dates between two dates

I have a leave system where user select dates from and to dates let say 2018-02-26 - 2018-03-03 that is 6 days in total. On our portal it shows all users that is on leave. supposing that this user applied for 6 days leave, How am I going to display this user for 6 days on our portal?below is my code it works well but is show only for the current date.
$currentDate = date('Y-m-d');
$lf = Leave::where('leave_from', $currentDate)
->where('status', 'approved')
->get();
I am using eloquent. thanks
// Specify the start date. This date can be any English textual format
$date_from = "2018-02-03";
$date_from = strtotime($date_from); // Convert date to a UNIX timestamp
// Specify the end date. This date can be any English textual format
$date_to = "2018-02-10";
$date_to = strtotime($date_to); // Convert date to a UNIX timestamp
// Loop from the start date to end date and output all dates inbetween
for ($i=$date_from; $i<=$date_to; $i+=86400) {
echo date("Y-m-d", $i).'<br />';
}
You can use datetime function in PHP.
$first_date = new DateTime($currentDate);
$last_date = new DateTime($if);
$difference = $first_date->diff($last_date);
echo $difference->d.' days;
if you want month and year use $difference->m and $difference->y.And if you want accurate days even dates are negative use below one.
$result = $first_date->diff($last_date)->format("%r%a");
source:/ datetime
You can use date_diff() function:
$interval = date_diff($currentDate, $lf);
echo $interval->format('%d');
more on: http://php.net/manual/en/function.date-diff.php; https://www.w3schools.com/php/func_date_date_diff.asp
You can use DATEDIFF to get difference directly from query.
Select abs(DATEDIFF(`date_to`,`date_from`)) as diff from leaves;
In laravel you can write it as
$lf = Leave::where('status', 'approved')
->select(DB::raw("abs(DATEDIFF(`date_to`,`date_from`)) as diff"),"*")
->get();
Be sure to use where('leave_from', $currentDate), I think it's not necessary.
You can use DateTime function of PHP
in your case
$currentDate = date('Y-m-d');
$currentDate = new DateTime($currentDate);
$leaveDate = new DateTime($leaveFrom);
$difference = $currentDate->diff($leaveDate);
You will get result like
DateInterval Object ( [y] => 0 [m] => 0 [d] => 5 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 5 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
$many_days=0;
$date_from = "2018-02-26";
$date_to = "2018-03-03";
for ($i=strtotime($date_from); $i<=strtotime($date_to);
$i+=86400) {
$many_days++;
}
echo "leaves $many_days";

Calculate time difference in php

I am trying to calculate time different between 3 different dates
1. Start date
2. End date
3 current date
I have been researching on how to calculation but couldn't find any exact example.
Any assistance in resolving this would be appreciated.
function getweekSartEndDate($date){
$cur_date = strtotime($date); // Change to whatever date you need
// Get the day of the week: Sunday = 0 to Saturday = 6
$dotw = date('w', $cur_date);
if($dotw>1){
$pre_monday = $cur_date-(($dotw-1)*24*60*60);
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==1){
$pre_monday = $cur_date;
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==0){
$pre_monday =$cur_date - (6*24*60*60);;
$next_sunday = $cur_date;
}
$date_array = array();
$date_array['weekStart'] = $pre_monday;
$date_array['weekEnd'] = $next_sunday;
return $date_array;
}
The above is the example code i got so far, and i was able to get the start and end dates of a week as seen below:
$weekStart = date('Y-m-d H:i:s', $weekInfo['weekStart']);
$weekEnd = date('Y-m-d H:i:s', $weekInfo['weekEnd']);
My challenges is how to get the time difference in 'Y-m-d H:i:s' date format from the current time.
You can use
$currentDate = date('Y-m-d H:i:s');
$currentDate = new DateTime($currentDate);
$leaveDate = new DateTime($leaveFrom);
$difference = $currentDate->diff($leaveDate);
You will get result as follow
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
You need basic knowledge on how to do number comparisons in PHP.
Convert your date strings to a UNIX-timestamp with strtotime
$d = strtotime("19/10/2016 14:48:21");
// 1519646232
When the dates are in UNIX-timestamp format, it's easy to compare them with any regular comparison operators as int numbers.
EDIT
Difference in seconds:
$diffBetweenStartAndNow = strtotime( $date_array['weekStart'] ) - time();
$diffBetweenEndAndNow = strtotime( $date_array['weekEnd'] ) - time();

How to calculate time difference between SQL time and PHP time

I have set times in SQL in this format: 2016-01-03 12:13:26.
I would like to calculate the number of hours and minutes (if hours<1) going from NOW() to that particular SQL time.
I've been looking at all the different threads here but I can't seem to grasp how to convert PHP different time formats to SQL's.
This is the code I've been using, but this will only give me back hours up to 12, and minutes also. Don't know how to use it with days.
$now = date("d/m/Y h:i:s");
$commentime = strtotime($SQLTIME);
$timetocomment = $now - $commentime;
For instance, this code will yield "12 hours ago" for data I posted 24 hours ago to SQL.
How can I do it? Thank you.
This is my suggestion to use date() in this format date("Y-m-d h:i:s"). Than you will get the complete difference in an array.
function dateDifference($date_1 ,$date_2)
{
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
return $interval;
}
$now = date("Y-m-d h:i:s");
$sqlTime = "2016-01-03 12:13:26";
$DateDiffArr = dateDifference($now,$sqlTime);
echo "<pre>";
print_r($DateDiffArr);
Result Is:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 22
[i] => 45
[s] => 55
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 1
[days] => 0
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
In resultant array, you can get the all difference as you need like in years, months, days, minutes, seconds etc.

Strange behaviour of PHP DateTime Class

I'm trying to get the time difference in milliseconds.
$_SESSION['startTime'] = time();
$to_time = time();
//I call the code from here after a delay, say 4 seconds
$from_time = $_SESSION['startTime'];
$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);
print_r( $d1->diff($d2));
I print the result after 4 seconds and the result is somewhat like this:
DateInterval Object
(
[y] => 4 //---- Problem, this value should be +
[m] => 0 // |
[d] => 0 // |
[h] => 0 // |
[i] => 0 // |
[s] => 0 //<-here-----------------------------+
[invert] => 1
[days] => 1461
)
[s] should have been 4. why the 4 is in the year section?
What am I doing wrong?
UPDATE - Solved
$to_time = (microtime(true));
$from_time = ( $_SESSION['startTime']);
$diff = $to_time - $from_time;
print $diff;
Prints
3.xxxxxx
You must specify the formatting. You're sending in a unix timestamp into DateTime, therefor:
$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);
Becomes
$d1 = new DateTime('#'.$from_time);
$d2 = new DateTime('#'.$to_time);
The # symbol tells DateTime that I'm using a Unix Timestamp.
The constructor for DateTime accepts a string as a parameter not a timestamp, which is why you are seeing the "strange behaviour".
You need to expressly set the timestamp after insantiating a DateTime object:-
$from_time = $_SESSION['startTime'];
$d1 = new DateTime();
$d1->setTimestamp($from_time);

Categories