Find out the time between two timeslots? - php

I have two times start_time=2009-12-01 9.30 pm and end_time=2009-12-01 11.30 pm(YYYY-MM-DD).If the user do any activity between these times ie at 2009-12-01 10.30 pm I need to tell him you are not valid to do this activity...
The two times 2009-12-01 9.30 pm and 2009-12-01 11.30 pm is taken from database.The time 2009-12-01 10.30 is given by user.
My question is how can I find the time 10.30pm is occured inbetween 9.30pm to 11.30pm...
I do my program in PHP

Use strtotime() to convert the strings into Unix seconds. Then a simple
if ($time1 < strtotime(10:30...) && strtotime(10:30...) < $time 2)
{
//do your stuff;
}

$start = strtotime($start_time);
$end = strtotime($end_time);
$user = strtotime($user_time);
if($user > $start && $user < $end) die('You are not allowed');

You can use database query or PHP. In PHP:
$timeStart = strtotime('2009-12-01 11.30');
$timeEnd = strtotime('2009-12-01 09.30');
$time = strtotime('2009-12-01 10.30');
if($time > $timeStart && $time < $timeEnd) {
echo "Between given times.";
}

convert "2009-12-01 9.30 pm" and "2009-12-01 11.30 pm" to unix timestamps, then compare those with <:
if ($start <= $event && $event < $end)
complain();
} else {
proceed();
}

There is no need to do any excessive PHP handling when you can simply use a SQL query:
SELECT 1 FROM your_table_name WHERE '2009-12-01 10:30:00' BETWEEN start_time AND end_time;
This will return 1 or more result(s) if the user activity occurs between any start and end times within the database. Please note you should have a leftmost prefix index on your table for (start_time, end_time).
Just check your query results. If you have a row count greater than or equal to 1 you know that the user activity falls between start and end times in your database.

Related

How to check two times in a time range using php

I have two times like start_time and end_time and also having a time range like a start time and a end time. I want to check start_time and end_time are in the range of start time and end time or not. How to check that.
$start_time1 = 10:15 am; //! time table start time
$end_time1 = 12:30 pm; //! time table end time
$strattime2 = 10:00 am; //! time range - start time
$endtime2 = 1:00 pm; //! time range - end time
How to resolve this problem?
Just check the boundary of the range. The query must be started on or after the range and must be ended on or before the range ends. So
function check($queryStart, $queryEnd, $rangeStart, $rangeEnd) {
return ($queryStart >= $rangeStart && $queryEnd <= $rangeEnd);
}
If you want to check whether the query is overlapping the range or not, you should check whether the query ends before the range start or the query starts after the range end.
function overlap($queryStart, $queryEnd, $rangeStart, $rangeEnd) {
return !($queryEnd < $rangeStart || $queryStart > $rangeEnd);
}
you may convert all the times to DateTime() Objects and then check the difference like so:
<?php
function startStopTimeIsWithinRange($startTime='10:15', $stopTime='12:30') {
$dateStart = new DateTime('2016-10-30 ' . $startTime); //<== IGNORE, THE DATE. NOTICE THE TIME
$dateStop = new DateTime('2016-10-30 ' . $stopTime); //<== IGNORE, THE DATE. NOTICE THE TIME
$rangeStart = new DateTime('2016-10-30 10:00'); //<== IGNORE, THE DATE. NOTICE THE TIME
$rangeStop = new DateTime('2016-10-30 13:00'); //<== IGNORE, THE DATE. NOTICE THE TIME
if($dateStart >= $rangeStart && $rangeStop >= $dateStop){
return true;
}
return false;
}
var_dump( startStopTimeIsWithinRange('10:15', '12:30') ); //<== NOTICE THE COLON (:) AND NOT DOT (.)

Condition for specific range of time to identify Shift

I have a piece of PHP program that would supposedly identify the Shift time of a user when they login.. see below actual script condition.
$dt = new DateTime(date('H:i:s'));
$dt->setTimezone( new DateTimeZone("Asia/Manila") );
$timeNow = $dt->format('H:i:s');
if (strtotime($timeNow) >= mktime(07,0,0) && strtotime($timeNow) < mktime(15,0,0)){
$shift = "2nd [0700H - 1500H]";
}elseif(strtotime($timeNow) >= mktime(15,0,0) && strtotime($timeNow) < mktime(23,0,0)){
$shift = "3rd [1500H - 2300H]";
}else{
$shift = "1st [2300H - 0700H]";
}
The script above is working but there are records that falls into wrong shift.. for example a user access the page in 7:10AM which means should be in 2nd Shift but instead.. it falls into 1st Shift
I don't know what have I missed in this control flow.. so if anyone from here can help and share ideas that would be very much appreciated. Thank you!
There's a difference between using DateTime::setTimezone() and applying a timezone in the DateTime constructor. The former, converts the existing time to the DateTimezone specified as the argument to DateTime::setTimezone(), and the latter, assumes that the supplied formatted date is already in that timezone.
You're saying you want to know whether right now it's between 7 am and 3 pm in Manila, or between 3 pm and 11 pm, etc... So the idea is to compare only within that timezone. There is no need to do any timezone conversion here whatsoever.
$now = new DateTime("now", new DateTimeZone("Asia/Manila"));
$shift2 = new DateTime("7:00 AM", new DateTimeZone("Asia/Manila"));
$shift3 = new DateTime("3:00 PM", new DateTimeZone("Asia/Manila"));
$shift1 = new DateTime("11:00 PM", new DateTimeZone("Asia/Manila"));
if ($now >= $shift2 && $now < $shift3) {
// It's shift 2
} elseif ($now >= $shift3 && $now < $shift1) {
// It's shift 3
} else {
// It's shift 1
}

Finding the difference between 2 dates in PHP

I am using PHP, jQuery AJAX and HTML to create a timesheet system, for this the user needs to select 2 dates within 1 month of each other. The system as yet is working and shows (very limited) data.
BUT! When I actually select a date over the month limit (i.e. 2 months further than the start or another year after the start), it still shows the table with the data.
For this I have this check:
$dt1 = new DateTime($_REQUEST['startdate']);
$dt2 = new DateTime($_REQUEST['enddate']);
$diff = date_diff($dt1, $dt2);
// I have tried this the other way around and get the same result...
if($diff->m > 1 || $diff->y > 1)
{
print("<center><strong>Time between dates it too great<br />Please choose another date or time within a month of each other</strong></center>");
die();
}
The dates are passed by a jQuery datepicker object via AJAX, and the dates I use, for example, are passed as such:
11/14/2015 (start date) && 12/14/2015 (end date) - should show data
09/14/2015 (start date) && 12/14/2015 (end date) - should not show data but does
11/14/2015 (start date) && 12/14/2016 (end date) - should not show data but does
There is a check in place that sees if the dates given start before the other and this works, I have tried the same kind of thing for this check, but without success, this check is as such:
function CountDaysBetween($startDate, $endDate)
{
$begin = strtotime($startDate);
$end = strtotime($endDate);
if ($begin > $end) {
echo "start date is in the future! <br />";
return;
} else {
$no_days = 0;
$weekends = 0;
while ($begin <= $end) {
$no_days++; // no of days in the given interval
$what_day = date("N", $begin);
if ($what_day > 5) { // 6 and 7 are weekend days
$weekends++;
};
$begin += 86400; // +1 day
};
$working_days = $no_days - $weekends;
return $working_days + 1;
}
}
Edit
Dates 2 or more months apart within the same year work, tested again and this is the case, but dates into the next year do not
In your first part of the php code, you have put this operator>, but the problem is it means, everything Smaller than 1, not everything that is smaller than one or equal to 1. The easy solution is to change the operators to >=; which means everything that is equal to 1 or smaller than 1.
The date_diff constructs in PHP suck monkeyballs. Far more practical is to use straight comparisons instead:
$dt1 = new \DateTime($_REQUEST['startdate']);
$dt2 = new \DateTime($_REQUEST['enddate']);
$dt1->add(new \DateInterval('P1M'));
echo ($dt1 < $dt2 ? 'Less' : 'More') . ' than a month';
Also please do not use $_REQUEST, it has potentially terrible security issues. You should use $_GET, $_POST or $_COOKIE according to what you explicitly expect.

PHP function to compare now time to time in database

I am trying to show different content based on the time recorded in my database.
From 1800 pm to 0800 am show content B.
The rest of the remaining time show content A.
My database field is storing time field so in database 1800 pm is stored as 18:00:00 same goes to 0800 am, it is stored as 08:00:00.
Below is my logic to get content B when time is between 18:00:00 to 08:00:00:
$now = strtotime(date('H:i:s'));
$time_from = strtotime($data['date_from']); //18:00:00
$time_to = strtotime($data['date_to']); // 08:00:00
if($now >= $time_from && $now <= $time_to){
echo 'content A';
}
The above code will only work if my $time_to is within 23:59:59 as $now will always be bigger than 08:00:00. Lets say the time now is 23:30:00, my codes will never echo "content A" out because 23:30:00 is bigger than 08:00:00.
How can i make the logic work to check by time only then to display the content?
#All, im editing the code again. Yes. i did put $now = strtotime(date('H:i:s'));. But it is not working as well. Firstly, the current now unix timestamp will always be bigger than 08:00:00 unix timestamp. let's say the time now is 23:30:00. The unix timestamp will always be bigger than 08:00:00.
if (date("H:i") >= '08:00' && date("H:i") <= '18:00') {
// Retrieve content 'A'
} else {
// Retrieve content 'B'
}
before making the comparision, you need to strtotime() your $now variable as well, try:
$now = date('H:i:s');
$time_from = strtotime($data['date_from']); //18:00:00
$time_to = strtotime($data['date_to']); // 08:00:00
$now_str = strtotime($now);
if($now_str >= $time_from && $now_str <= $time_to){
echo 'content A';
}

Check if appointment time fits users working time with SQL - Wrong proposal during night

I defined hours where an employee is working aka working hours, e.g.
$start = "09:00:00";
$end = "18:00:00";
A user can now select an appointment, and the query should validate it, e.g.
$appointment_start = "09:00:00";
$appointment_end = "10:00:00";
My SQL query should now check if the employee is working at that specific time. If that is the case, propose this appointment to the user. This is how I do it:
...
AND w.start <= '$appointment_start'
AND w.end >= '$appointment_end';
There seems to be a problem during night when the day changes, e.g. when start is 23:00:00 and end is 00:30:00. This should not be a valid appointment time, but my query proposes it:
start substr: 23:00:00 || end substr: 00:00:00
start substr: 23:30:00 || end substr: 00:30:00
How do I have to change the WHERE statement of my SQL query to fix this issue?
You could use a datetime rather than just a time to avoid this issue altogether.
Or you could do something like:
AND (( w.start < w.end
AND w.start <= '$appointment_start'
AND w.end >= '$appointment_end') OR
( w.start > w.end
AND w.start >= '$appointment_start'
AND w.end <= '$appointment_end' ) )
Basically, you invert your comparison operators when start happens after end.
If you are unable to use a datetime you could massage your values.
$appointment_end = ($appointment_end < $appointment_start) ? $appointment_end + [24hours] : $appointment_end;
$end = ($end < $start) ? $end + [24hours] : $end;
Basically if the end time is less than the start time, assume it's the next day and add 24 hours, then do the check as normal. (not sure of the syntax in php to add the [24hours])

Categories