I want to compare two times.
But first i would like to count up one time for 110 minutes.
What did i do wrong?
Code:
$current_time = date("H:i");
$match_start = strtotime("H:i", "19:30"); // <- Value from database
$match_end = strtotime("+110 minutes", $match_start)
if($current_time > $match_start && $current_time < $match_end) {
//Match has started
}
Another solution using strtotime()
$current_time = strtotime(date("H:i")); // or strtotime(now);
$match_start = strtotime("14:30");
$match_end = strtotime("+110 minutes", $match_start);
if($current_time > $match_start && $current_time < $match_end) {
echo "Match has started";
}
Working demo
It might have to do with the fact that you are comparing strings, not actual time values. Try using DateTime() which makes this clearer.
$current_time = new DateTime();
$match_start = new DateTime("19:30");
$match_end = (new DateTime("19:30"))->modify("+110 minutes");
if($current_time > $match_start && $current_time < $match_end) {
//Match has started
}
First, create datetime like this (change your datetimezone):
$match_start = "19:30"; // <- Value from database
$current_time = new DateTime('', new DateTimeZone('Europe/Rome'));
$start = new DateTime($match_start, new DateTimeZone('Europe/Rome'));
$end = new DateTime($match_start, new DateTimeZone('Europe/Rome'));
Then add 110 minutes to end time:
$end->add(new DateInterval('PT110M'));
Finally:
if($current_time > $start && $current_time < $end)
{
//Match has started
}
Related
I want to set a fix time variables in php for my if and else condition.
For example:
$startTime = '08:00:00';
$endTime = '16:00:00';
$totalhrs = $endTime - $startTime;
echo $totalhrs;
Anyone know how to declare the time in PHP?
Thanks for the help
$startTime = strtotime('08:00:00');
$endTime = strtotime('16:00:00');
$totalhrs = ($endTime - $startTime) / 3600;
echo $totalhrs;
you can use datetime object for this case
$startTime = new DateTime('08:00:00');
$endTime = new DateTime('16:00:00');
$totalhrs = $startTime->diff($endTime)->h;
You can try the below function to check timestamps. If you don't pass it a second parameter, it will evaluate if the first time has passed the CURRENT time, otherwise it will compare the first time against the second.
Function timeHasPassed($Time, $Time2 = 0) {
If ($Time2 != 0) {
$Now = new DateTime($Time2);
} Else {
$Now = new DateTime();
}
$Then = new DateTime($Time);
If ($Now > $Then) {
Return TRUE;
} Else {
Return FALSE;
/*
You can also use the below code to print out how long is left until the timestamp has passed. Keep in mind, this will return TRUE if tested as a boolean so maybe consider returning a different datatype instead of TRUE if you decide to go this route.
$Time = new DateTime($Time);
$Now = new DateTime();
$Remainder = $Time->diff($Now);
$Remainder = $Remainder->format("%h hours, %i minutes, and %s seconds!");
return $Remainder;
*/
}
}
I want to compare the interval of two datetimes to see if the interval is in the past, in the future or now.
$current_time = new DateTime();
$datetime1 = new DateTime('2018-03-17 18:25:00');
$datetime2 = new DateTime('2018-03-17 20:00:00');
if($current_time >= $datetime1 && $current_time <= $datetime2){
// now
} elseif($current_time >= $datetime1){
// past
} elseif($current_time <= $datetime1){
// future
}
EDIT:
Sorry, just realised posting my whole real code would make it easier for everyone.
The example above does work but it doesnt work when I loop thru the db using more than one interval from there
function interval(){
....
while($row = $result->fetch_assoc()){
$start_time = $row['start_time'];
$end_time = $row['end_time'];
$now = new DateTime();
$datetime1 = new DateTime($start_time);
$datetime2 = new DateTime($end_time);
if($now >= $datetime1 && $now <= $datetime2){
// now
}elseif($now < $datetime1 && $now < $datetime2){
// past
}elseif($now > $datetime1 && $now > $datetime2){
// future
}else{
// fail?
}
}
}
date returns a string. If you actually want to use a real DateTime object, then you need to do something like:
$now = new DateTime();
$other = new DateTime('2018-03-18 17:45:00'); //note: example made off the top of my head... value presented may not work
if ($now < $other) {
//do something
}
More information can, as always, be found in the PHP manual: https://secure.php.net/manual/en/class.datetime.php
As your dates are already string just compare them like that
$current_time = date("Y-m-d H:i:s");
$datetime1 = '2018-03-17 18:25:00';
$datetime2 = '2018-03-17 20:00:00';
if($current_time >= $datetime1 && $current_time <= $datetime2){
// now
} elseif($current_time >= $datetime1){
// past
} elseif($current_time <= $datetime1){
// future
}
Can you expand why your code isn't working as intended?
Below is how I would approach the question.
date_default_timezone_set('UTC');
$current_time = new DateTime();
$compareWith = new DateTime('2018-03-16 18:25:00');
if ($current_time >= $compareWith) {
//whatever your heart desires
}
else{
//whatever your heart desires
}
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
How can I check if the time of $now is within the timerange?
There are several ways to achieve that by using Carbon. One of the easiest ways is using createFromTimeString and between methods:
$now = Carbon::now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00')->addDay();
if ($now->between($start, $end)) {
// ¯\_(ツ)_/¯
}
Try this:
$time = Carbon::now();
$morning = Carbon::create($time->year, $time->month, $time->day, 8, 0, 0); //set time to 08:00
$evening = Carbon::create($time->year, $time->month, $time->day, 18, 0, 0); //set time to 18:00
if($time->between($morning, $evening, true)) {
//current time is between morning and evening
} else {
//current time is earlier than morning or later than evening
}
The true in $time->between($morning, $evening, true) checks whether the $time is between and including $morning and $evening. If you write false instead it checks just if it is between the two times but not including.
Actually, you could leave true away because it is set by default and not needed.
Check here for more information on how to compare dates and times with Carbon.
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$time = $now->format('H:i:s');
if ($time >= $start && $time <= $end) {
...
}
Should do it, but doesn't take date into consideration
You can reverse check algorithm.
<?php
$pushChannel = "general";
$now = Carbon::now();
$start = Carbon::createFromTime(8, 0);
$end = Carbon::createFromTime(22, 0);
if (!$now->between($start, $end)) {
$pushChannel = "silent";
$restrictStartTime = Carbon::createFromTime(22, 0, 0); //carbon inbuild function which will create todays date with the given time
$restrictEndTime = Carbon::createFromTime(8, 0, 0)->addDays(1); //this will create tomorrows date with the given time
$now = Carbon::now();
if($now->gt($restrictStartTime) && $now->lt($restrictEndTime)) {
.....
}
Please Try below code,
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$nowTime = $now->hour.':'.$now->minute.':'.$now->second;
if(strtotime($nowTime) > strtotime($start) && strtotime($nowTime) < strtotime($end) ) {
echo 'YES';
} else {
echo 'NO';
}
What Chris is trying to point out is if the endtime crosses over midnight then you must account for that.
This is not the cleanest way to do it but here is a method that seems to work.
private function isNowBetweenTimes($timezone, $startDateTime, $endDateTime) {
$curTimeLocal = Carbon::now($timezone);
$startTime = $curTimeLocal->copy();
$startTime->hour = $startDateTime->hour;
$startTime->minute = $startDateTime->minute;
$endTime = $curTimeLocal->copy();
$endTime->hour = $endDateTime->hour;
$endTime->minute = $endDateTime->minute;
if ($endTime->lessThan($startTime))
$endTime->addDay();
return ($curTimeLocal->isBetween($startTime, $endTime));
}
This example only cares about the hour and minutes and not the seconds but you can easily copy that as well. The key to this is comparing start and end time before comparing them to the current time and add a day to end time if end time is less than start time.
For complete solution which supports all start and end time range you can use bitwise XOR.
/*
* must using hours in 24 hours format e.g. set 0 for 12 pm, 6 for 6 am and 13 for 1 pm
*/
private $startTime = '0';
private $endTime = '6';
$currentHour = \Carbon\Carbon::now()->hour;
$start = $this->startTime > $this->endTime ? !($this->startTime <= $currentHour) : $this->startTime <= $currentHour;
$end = $currentHour < $this->endTime;
if (!($start ^ $end)) {
//Do stuff here if you want exactly between start and end time
}
an updated version of #AliN11's answer taking into account ranges accross two days or in the same day
$now = now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00');
if ($start > $end) {
$end = $end->addDay();
}
if ($now->between($start, $end)||$now->addDay()->between($start, $end)) {
//add statements
}
<?php
$now = date("H");
if ($now < "20") {
echo "Have a good day!";
}
Try this :
$start = 22; //Eg. start hour
$end = 08; //Eg. end hour
$now = Carbon::now('UTC');
if( $start < $now->hour && $now->hour < $end){
// Do something
}
#AliN11's (currently top) answer is good, but doesn't work as one would immediately expect, after midnight it just breaks, as raised in the comments by #Sasha
The solution is to reverse the logic, and check if the time is not between the inverse hours.
Here is an alternative that works as one would expect:
$now = Carbon::now();
$start = Carbon::createFromTimeString('08:00');
$end = Carbon::createFromTimeString('22:00');
if (! $now->between($start, $end)) {
// We're all good
}
Yes, the midnight plays a vital role in time duration. We can find now() being the given time range as follows:
$now = Carbon::now();
$start = Carbon::createFromTime('22', '00');
$end = Carbon::createFromTime('08', '00');
if ($start->gt($end)) {
if ($now->gte($start)) {
$end->addDay();
} elseif ($now->lte($end)) {
$start->subDay();
} else {
return false;
}
}
return $now->between($start, $end);
i'm trying to find and calculate between startime, finish time as: starttime + 1 hour and current time. if current time is between start and finish i must be print message such as please try after 1 hour:
$current_date_time = new DateTime("now", new DateTimeZone("Asia/Tehran"));
$user_current_time = $current_date_time->format("H:i:s");
$start_limit_time = date("H:i:s",strtotime('2015-09-15 14:57:31'));
$finish_limit_time = date('H:i:s', strtotime($start_limit_time) + (60 * 60 * 1));
$date1 = DateTime::createFromFormat('H:i:s', $user_current_time);
$date2 = DateTime::createFromFormat('H:i:s', $start_limit_time);
$date3 = DateTime::createFromFormat('H:i:s', $finish_limit_time);
if ($date1 > $date2 && $date1 < $date3)
{
echo 'here';
}
this code is not correct and i can not fix that,
You can try this, it shows the difference in minutes:
$current_date_time = new DateTime("now", new DateTimeZone("Asia/Tehran"));
$user_current_time = $current_date_time->format("H:i:s");
$start_limit_time = date("H:i:s",strtotime('2015-09-15 14:57:31'));
$finish_limit_time = date('H:i:s', strtotime($start_limit_time) + (60 * 60 * 1));
$date1 = DateTime::createFromFormat('H:i:s', $user_current_time);
$date2 = DateTime::createFromFormat('H:i:s', $start_limit_time);
$date3 = DateTime::createFromFormat('H:i:s', $finish_limit_time);
if ($date1 > $date2 && $date1 < $date3)
{
$tryAgainIn = $date3->diff( $date1 );
// just minutes
echo "try again in ".$tryAgainIn->format( "%i minutes" );
// or hours and minutes
$hours = $tryAgainIn->format('%h');
$minutes = $tryAgainIn->format('%i');
echo "try again in $hours hours and $minutes minutes";
}
For more information take a look at: DateTime::diff
At first you should avoid operating with strings format, as they should only be used IMHO to printing and retrieving data from outside. Use only timestamp or OOP methods.
I believe, that this is something you are looking for:
$startTime = new DateTime('2015-09-15 14:57:31');
$endTime = clone $startTime;
$endTime->modify('+1 hour');
if ($startTime->getTimestamp() <= time() && time() < $endTime->getTimestamp()) {
echo 'here';
}
I wonder why you need to use H:i:s format. Can you give some bigger picture?
Edit: Try this, as prior to now I did not fully understand what you want to do ;)
$origin = new DateTime('2015-09-15 14:57:31');
$startTime = new DateTime('today '.$origin->format('H:i:s'));
$endTime = clone $startTime;
$endTime->modify('+1 hour');
if ($startTime->getTimestamp() <= time() && time() < $endTime->getTimestamp()) {
echo 'here';
}
if
$_POST['SelectedDate1'] = 2013/08/05
and
$_POST['SelectedDate2'] = 2013/08/07
How can I set a variable which gives me back the number of days (2 in this case) to then echo it as result
I'm looking for a solution that can cover any calendar combination.
Is there any global function in php.
I think, in the following Documentation on PHP.net is exactly what you're trying to do.
http://nl3.php.net/manual/en/datetime.diff.php
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
In your case:
<?php
$first = new DateTime($_POST['SelectedDate1']);
$second = new DateTime($_POST['SelectedDate2']);
$passed = $first->diff($second);
var_dump($passed->format('%R%a days'));
For more formats, next to %R%a, see: http://nl3.php.net/manual/en/function.date.php
<?php
$days = (strtotime($_POST['SelectedDate2']) - strtotime($_POST['SelectedDate1'])) / 86400;
example:
<?php
$_POST['SelectedDate1'] = '2013/08/05' ;
$_POST['SelectedDate2'] = '2013/08/07' ;
$days = (strtotime($_POST['SelectedDate2']) - strtotime($_POST['SelectedDate1'])) / 86400;
var_export($days);
// output: 2
I use this function that I've found on this forum but I don't remember where :
function createDateRangeArray($start, $end) {
// Modified by JJ Geewax
$range = array();
if (is_string($start) === true) $start = strtotime($start);
if (is_string($end) === true ) $end = strtotime($end);
if ($start > $end) return createDateRangeArray($end, $start);
do {
$range[] = date('Y-m-d', $start);
$start = strtotime("+ 1 day", $start);
}
while($start <= $end);
return $range;
}
it returns a range of date as an array, then you just have to get the count
DateTime class is created for this:
$date1 = new DateTime('2013/08/05');
$date2 = new DateTime('2013/08/07');
$diff = $date1->diff($date2);
echo $diff->days;