comparing time in php error - php

i'm trying to compare the current time against 5 other times as a schedule but it's not working. Dates are fetched from the database here's the code
$now = new DateTime();
$date1 = new DateTime($pRow['date1']);
$date2 = new DateTime($pRow['date2']);
dates in database:
date1: 12:00
date2: 03:25
if($now->format('h:i') >= $date1->format('h:i') && $now->format('h:i') <= $date2->format('h:i')){
echo "date2";
}
else{
echo "no";
}
the result is always no (code edited to be simple and faster to solve the problem)

if($now >= $date5 && $now <= $date5)
wrong data is comparing

When using the h modifier for time you are working with only 1-12 for hours. This means 2pm is just 2 and 11am is 11. Therefore 11 > 2 which breaks your math. Use H instead.
$now = date("H:i",strtotime("now"));
$date1 = date("H:i",strtotime($pRow['date1']));
$date2 = date("H:i",strtotime($pRow['date2']));
$date3 = date("H:i",strtotime($pRow['date3']));
$date4 = date("H:i",strtotime($pRow['date4']));
$date5 = date("H:i",strtotime($pRow['date5']));
Or, better yet, use DateTime which are comparable.
$now = new DateTime();
$date1 = new DateTime($pRow['date1']);
$date2 = new DateTime($pRow['date2']);
$date3 = new DateTime($pRow['date3']);
$date4 = new DateTime($pRow['date4']);
$date5 = new DateTime($pRow['date5']);

This code was already at stackoverflow, try to use it :)
$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
echo "The Time that was entered is behind";
}

Related

How to find the Time Difference between a PM time and AM time?

In my form there are 2 Time Pickers where user can select a from time and to time. It doesn't have a date associated with it. And for a report generating purpose I've to calculate the time difference between them. It works perfectly to if the From and to Time is "06:00 to 10:00" but if the from and to time is "21:00 to 02:00" I get a time difference of 19 hours. Could you please help me to fix this.
For this case "21:00 to 02:00" the time difference should be 5 hours.
This is the Code
$datetime1 = new \DateTime('09:30 PM');
$datetime2 = new \DateTime('02:00 AM');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh');
exit;
The difference becomes negative If $totime is less than $fromtime.
DateInterval->invert == 1 indicates that. This is used with this short solution to correct the result.
$fromtime = '09:30 PM';
$totime = '02:00 AM';
$diff = date_create($fromtime)->diff(date_create($totime));
$hours = $diff->invert ? 24-$diff->h : $diff->h;
echo $hours; //5
Since you have 2 date pickers one for from time and another to time, the former will always be smaller than the latter. Hence when from time is larger than to time it means user has selected to from the next day. If we don't add a date for calculating difference, PHP will assume today's date by default. We can easily fix this by adding a condition to compare the times and prepend the dates accordingly. Below is the updated code.
<?php
$fromtime = '09:30 PM';
$totime = '02:00 AM';
$now = new \DateTime();
$today = $now->format('Y-m-d'); // Store current date
$now->add(new DateInterval('P1D')); // Add one day to current date to get next date
$nextDay = $now->format('Y-m-d'); // Store next date
if($fromtime > $totime) // If from time is bigger than to time, it means to is a next day
{
$fromdatetime = "$today $fromtime";
$todatetime = "$nextDay $totime";
}
else
{
$fromdatetime = "$today $fromtime";
$todatetime = "$today $totime";
}
$datetime1 = new \DateTime($fromdatetime);
$datetime2 = new \DateTime($todatetime);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh');
?>

Unable to correctly calculate date with "0000-00-00" date in php

I have two date like this
$date1 = "2018-11-07";
$date2 = "2018-11-12";
I want to compare these two date so i could get a range of day between these date. I used DiffDate function. It's looks like below syntax.
$datediff1 = new DateTime($date1);
$datediff2 = new DateTime($date2);
$interval = $datediff2->diff($datediff1);
echo $interval->d; // will return 5
I got the function, but i have problem when one from these two date had a value like "0000-00-00". They started to looks like this.
$date1 = "2018-11-07";
$date2 = "0000-00-00";
$datedif1 = new DateTime($date1);
$datediff2 = new DateTime($date2);
$interval = $datediff2->diff($datediff1);
echo $interval->d; // will return 8
//// If i reverse the date like $datediff1->diff($datediff2);
//// it will return 7 instead
My question is how could i prevent these two dates return 0 when one or all dates have "0000-00-00" value ? I have tried like using if...else....
if($date1 == "0000-00-00" || $date2 == "0000-00-00"){
$interval = "0";
echo $interval;
}else {
$interval = $date2->diff($date1);
$i = $interval->d;
}
Is there any better way to do it rather than using if else statement ?
SEE IT ONLINE HERE
PS : I am using PHP 5.6
You can rely on the fact that the timestamp starts with 1970 so a 0000 year would result a negative timestamp :
$date1 = "2018-11-07";
$date2 = "0000-00-00";
$datedif1 = new DateTime($date1);
$datediff2 = new DateTime($date2);
// check if strtotime returns a valid timestamp and the year is not 0000
$interval = (!strtotime($date1) ||
!strtotime($date2) || strtotime($date1) < 0 ||
strtotime($date2) < 0) ? 0 : $date2->diff($date1);
print_r($interval);
This needs to be refined because it won't work in all cases but it's working in your case.

how to show months and years from two date in PHP

I have $date1 = '2014-09-01' and $date2 = '2015-02-01'. Can I get months and years from $date1 to $date2 like this:
2014-sep
2014-oct
2014-nov
2014-dec
2015-jan
2015-feb
Instantiate DateTime objects and loop through them:
$date1 = new \DateTime('2014-09-01');
$date2 = new \DateTime('2015-02-01');
while ($date1 <= $date2) {
echo $date1->format('Y-M') . '<br>';
$date1->add(new \DateInterval('P1M')); // increase by one month
}
Result:
2014-Sep
2014-Oct
2014-Nov
2014-Dec
2015-Jan
2015-Feb
$date1 = new DateTime("2014-09-01");
$date2 = new DateTime("2015-02-01");
while ($date1 <= $date2) {
echo $date1->format("Y-M")."\n";
$date1->modify("+1 month");
}
Result:
2014-Sep
2014-Oct
2014-Nov
2014-Dec
2015-Jan
2015-Feb
Use DateTime and DateInterval class with couple of methods like add() to increment counter and format() to date formating using simple while loop
$startDate= new DateTime("2014-09-01");
$endDate = new DateTime("2015-02-01");
$oneMonth=new DateInterval('P1M'); //for 1 month interval
while ($startDate <= $endDate) {
print $startDate->format("Y-M")."\n"; //date formating as your requirement
$startDate->add($oneMonth); //increment counter by 1 month
}

how to compare my current time and date with db stored date

here i have stored two dates in db like start date as 2014-07-07 00:00:00 and end date as 2014-07-15 23:59:59. Now how can I check my current date between the two days
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$now = new DateTime();
$current_time = $now->format('Y-m-d H:i:s');?>
if date1 and date2 are retrieved from db and compare with current date it getting from server if it is between the two days it should be display end time from now.
USE :
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$cdate1 = new DateTime($date1);
$vdate1 = $cdate1->getTimestamp();
$cdate2 = new DateTime($date2);
$vdate2 = $cdate1->getTimestamp();
compare integers ($vdate1 and $vdate2) to each other
Result will be in seconds
Enjoy :)
Just as an Object Oriented style alternative you can create objects as instances of DateTime class, like these:
$date1 = new DateTime('2014-07-07 00:00:00');
$date2 = new DateTime('2014-07-15 23:59:59');
$now = new DateTime();
then, following your logic, you can compare if now is before or after the other dates, like:
var_dump($date2 > $now);
or you can retrieve an instance of DateInterval interface with:
$now_interval_from_date1 = $date1->diff($now);
and then use the format method to know exactly the time/day/etc.. differences, like:
$now_interval_from_date1->format("%R%H hours")
You can find the format params here:
http://www.php.net/manual/it/dateinterval.format.php
If the two dates are exactly in the same format, php allows string comparison.
So you can do the following:
if(strcmp($date1, $current_time) <= 0 and strcmp($date2, $current_time) > 0)
{
// The date is within the limits
}
strcmp is a safer function for string comparison
So, in your case, you could have the following:
<?php
$con=mysqli_connect("localhost","root","","proms"); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
date_default_timezone_set("America/New_York");
$current_time =date("h:i:sa");
$result = mysqli_query($con,"SELECT * FROM image");
while($row = mysqli_fetch_array($result)) {
if(strcmp($row['start_date'],$current_time) <= 0 && strcmp($row['end_date'],$current_time) > 0) {
// The date is within the limits
echo "yes";
}
}
?>
'start_date' and 'end_date' should be substituted with your fields' names.
You can do as following to compare current time between two dates
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$now = date('Y-m-d H:i:s');
$date1TimeStamp = strtotime($date1);
$date2TimeStamp = strtotime($date2);
$nowTimeStamp = strtotime($now);
if($date1TimeStamp <= $nowTimeStamp || $date2TimeStamp >= $nowTimeStamp){
$seconds_diff = $date2TimeStamp - $nowTimeStamp;
$days = $seconds_diff/(3600*24);
}else
echo 'No, out';
Edited calculation, now it displays remaining days time from now to end date.
if(strtotime('now') > strtotime($date1) && strtotime('now') < strtotime($date2)) {
$diff = strtotime($date2) - strtotime('now');
}
$diff then contains the difference between the two dates in miliseconds. Just convert miliseconds to days : hours : minutes (Mathematics ?)

PHP days difference

Hello i'm trying to make a php script that compares the date from one of my database records and todays date, if the difference in days is greater than 3, it will come out to true.
example:
$todays_date = date("Y-m-d"); <-- Todays date
$deal_date = $data["Deal Date"]; <-- Date from database
$interval = date_diff($todays_date, $deal_date); <--Difference
if($interval >= 3)
{
(something)
}
but every time i try this i get an error "date_diff() expects parameter 1 to be DateTime, string given" i know that to use date_diff both arguments have to be datetime, but i'm not sure how to get today's date in date and how to convert the date from the database into datetime.
Try this code:
$date1 = new DateTime('now');
$date2 = new DateTime($data['Deal Date']);
$interval = $date1->diff($date2);
if ($interval->format('%a') >= 3) {
...
}
More examples in PHP date_diff documentation.
CORRECT SYNTAX IS:
<?php
$datetime1 = date_create('now');
$datetime2 = date_create($data["Deal Date"];);
$interval = date_diff($datetime1, $datetime2);
$diff = $interval->format('%a');
if($diff >= 3)
{
(something)
}
?>

Categories