Time calculation activity in Php - php

I am working on a web application, in which a web user activity is to be block form half hour before of given time.
I need to calculate time half hour before of given time.
Means if a date and time give like 08/04/2015 16:00:00
now need to calculate time half hour before of the given time i.e. 08/04/2015 15:30:00 during this a web activity is blocked for end user.
Please give me suggestion and sample code in PHP.

you can take this for your refrence,
but you need to modify the code as per your requirements
$start_time = strtotime("2008-12-13 10:42:00"); // get this time while user loggs in
$end_time = strtotime(date('Y-m-d H:i:s'));// this is dynamic time, it changes everytime when the page is reloaded
$difference_in_minutes = round(abs($end_time - $start_time) / 60,2); // this will return the diference between two times in minutes
if($difference_in_minutes >= 30)
{
// do you 30 minutes block stuff here
}
let me know if any further classification needed

Related

Retrieve remaining time between two dates considering business hours

I am trying to write a php solution to calculate the planned end time considering the target in business hours.
It shouldn't consider some days (retrieved from setting saved in db) such as holidays.
Also business hours are retrieved from db (morning_from (8:30am), morning_to (1:00pm), evening_from (2:30pm), evening_to (6:30pm)).
I want to develop this script because I want that my page shows the remaining time for technical resolution of an opened ticket every day.
For example:
customer having contract with 10 working hours SLA opens a ticket
today (friday) 31/01/2020 16:00:00, considering that in the
noBusinessDays = array("saturday", "sunday") and businessHours set as mentioned before(8:30-13:00/14:30-18:30), the result will have to
be monday 3/02/2020 17:30:00.
Code example:
$noBusinessDays = array("saturday", "sunday");
$businessHours = array("morning_from" => "8:30", "morning_to" => "13:00", "evening_from" => "14:30", "evening_to" => "18:30");
$SLA = "10"; //hours
$ticketDate = new DateTime();
$ticketDate->setTimestamp(strtotime("31/01/2020 16:00:00"));
// I don't know how to use my arrays to say in this calculation how to use them
$maximumLimit = $ticketDate->add(new DateInterval("PT" . $SLA ."H"));
Thank you in advance.
You may use the following function
// intersection of 2 time intervals
// input - Unix timestamps (start,end)
// output - intersection in seconds
function time_union($b_1,$e_1,$b_2,$e_2)
{
return max(0,$e_1-$b_1 - max(0,$e_1-$e_2) - max(0,$b_2-$b_1));
}
You will start with an empty time interval [X, Y) where X is the timestamp of the ticket creation and Y initially is equal to X.
Then you start adding days to Y - one by one. Each time you expand the time interval to contain another day - you use the above function to check how much of the SLA hours are covered (i.e. overlapping) with the working hours in the day you have just added. If the day is marked as a holiday - you simple skip it and continue with the next date.
If you find out that SLA hours are partially covered with either the morning or evening business hours - you should simply subtract the extra hours.
In the end Y will be equal to the timestamp that you want to show in your application.
I think I'd break down the problem into pieces. After calculating the total number of days in the interval, first dispose of the trivial case that it's all happening in one week.
begin by calculating the number of "whole weeks." Each "whole week" is five business days. Subtract the corresponding interval of time and proceed. Now, look at the day-of-the-week of the start-date: each day adds a certain number of days. Then the day-of-week of the end date, likewise. You can then consider hour-of-the-day as needed.
Holidays are a simple table: if the day falls within the range, subtract one day.
Now ... having said all of that, the very first thing that I would do is to search GitHub and SourceForge! Because I am extremely sure that somebody out there has already done this. :-D
"Actum Ne Agas: Do Not Do A Thing Already Done."

PHP time values when Daylight Saving Time (DST)

I am developing a system to sign up, which should add up all the time someone has been online in my server. I want to take into account also those extra hours that have to be added or subtracted from the total when time changes due to DST.
It is easy to subtract an hour in the third Sunday of March, because I only have to check if the signing time was before 2AM and the sign-out time after 3AM; it is also easy when, in October, someone signs in before 2AM and signs out after 3AM, in that case, I only have to add an hour.
But what about signing in between 2 and 3AM (let's say 2:30) on the last Sunday of October? How would I know if it is the first time it is 2:30, or the second time? In the first case I should add half an hour to the total, whereas in the second case I should leave it as it was before.
Does PHP's time() function give different values when it is 2:30 for the first time than when it is for the second time? I assume it should, as it returns the number of seconds since the Unix Epoch, and it shouldn't be the same for both cases, but I would like to confirm it.
Edit 1:
This is the code to calculate the two cases I mentioned where it was easy enough:
(timeChangingDates is a function coded by myself, which given the year, it returns an array of length 2. In the first position there will be the last Sunday of March, in which time changes, and in the second position, the last Sunday of October)
($startTime and $endTime are DateTime objects in which sign-in and sign-out datetimes are stored)
// If sign-in time is before 2AM and sign-out time after 3AM add an hour(October)
if ((strtotime($startTime->format('Y-m-d H:i:s')) < strtotime(new DateTime($startTime->format("Y").'-10-'.timeChangingDates($startTime->format("Y"))[1].' 1:59:00')->format('Y-m-d H:i:s'))) && (strtotime($endTime->format('Y-m-d H:i:s')) > strtotime(new DateTime($startTime->format("Y").'-10-'.cambiosHorarios($startTime->format("Y"))[1].' 3:00:00')->format('Y-m-d H:i:s')))) {
$totalTime = $totalTime + 60;
// If sign-in time is before 2AM and sign-out time after 3AM subtract an hour(March)
} else if ((strtotime($startTime->format('Y-m-d H:i:s')) < strtotime(new DateTime($startTime->format("Y").'-3-'.timeChangingDates($startTime->format("Y"))[0].' 1:59:00')->format('Y-m-d H:i:s'))) && (strtotime($endTime->format('Y-m-d H:i:s')) > strtotime(new DateTime($startTime->format("Y").'-3-'.cambiosHorarios($startTime->format("Y"))[0].' 3:00:00')->format('Y-m-d H:i:s')))) {
$totalTime = $totalTime - 60;
}
I haven't tried any way to do the third case mentioned yet, as I cannot simulate time change on Windows. That is why I'd like to know if just using time() would work.

How do you rotate text strings contingent on the time of day, in PHP?

I am trying to rotate phone numbers depending on the time of day. If the time is between 8am and 5pm, it should show the 888 number. If it is after 5pm but before 8am it should show the 777 number. This is what I got thus far, but it only shows the 777 number as my output, even though the time is between the hours of 8am and 5pm.
$dayPhoneNumber = "1-888-888-8888";
$nightPhoneNumber = "1-777-777-7777";
$currentPhoneNumber = "";
$nowHour = date("H");
$startHour = 8;
$endHour = 17;
if ($nowHour >= $startHour && $nowHour <= $endHour){
echo $dayPhoneNumber;
} else {
echo $nightPhoneNumber;
}
My guess is your server's time is not the same as your computer's time. If you're using a hosting solution, your server may very well be across the country or on a different continent, meaning the time will be different.
If you just need to worry about one location and not where the end user is, then this should be easy to do. If you're on the West Coast of the US
date_default_timezone_set("America/Los_Angeles");
$hour = date("H", time());
Here is a list of Time Zones: http://www.php.net/manual/en/timezones.php
If you need to know the end user's time zone when determining the hour, here's a discussion on doing that: How to get client's timezone?
If you're dealing with time zone issues, you may also want to retrieve the time using UTC, and then add or subtract whatever number of hours to get to the correct time zone: get UTC time in PHP

Compare user's time zone with the website's office location time zone

I am working on a project where i need to SHOW the visitor of the website a message in the contacts area like:
Contact no: +91-99-3241-5285 [You can call us now]
The message is highlighted in the above line, now my question is, how to compare the user's time zone with the working hours of the company's office.
P.S. - Suppose the company is in INDIA, and its working hours are 9.00am to 5.00pm.
Any suggestions?
Use javascript to determine the users timezone offset:
http://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp
var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);
Then calculate e.g. the current time in INDIA (GMT + 5:30 if i'm not wrong) and show "you can call us now" if the resulting time is within the working hours.
var diff = gmtHours - 5.5; // -> difference between users timezone and india in hours
var indiaDate = new Date();
indiaDate.setTime(d.getTime() - (diff * 60 * 60 * 1000));
document.write("<br />Current time in India: " + indiaDate.toString());
See the working demo at: http://jsfiddle.net/roberkules/RLsw9/
The replies immediately below your question are correct. There should be no need to know the client's time zone to calculate whether or not the current time is within hours of operation. It doesn't really matter whether it's currently 8:00am US Pacific, 11:00am US Eastern, or 11:00pm in Manila, Philippines. The important thing is what time it is relative to the business hours, not relative to the client.
Typically on all web servers I run, I set the server time to UTC. When people enter their hours, either have them enter it in GMT or, if you want them to be able to enter the hours in their local time, have a time zone list or combo box on the page. You can use PHP's DateTimeZone::listAbbreviations() function to help.
So, for example, say someone enters that their hours are from 9:00am to 5:00pm in the Asia/Calcutta time zone. When you're using the time for calculations, do something like this, assuming you have rows named something like hrs_start, hrs_end, and hrs_tz:
$hrs_tz = new DateTimeZone($row['hrs_tz']);
$hrs_start = new DateTime($row['hrs_start'], $hrs_tz);
$hrs_end = new DateTime($row['hrs_end'], $hrs_tz);
Now you can use these hours to calculate whether or not the hours are in or out of their business hours.

How to ensure that one time is always less than another

I've got two times that need to be stored into a database. The time format is hh:mm:ss with NO DATE. These times can be changed by the users on the system. One is a time on and the other is a time off. The time off should always be greater than the time on within a 24 hour cycle.
Here is the part that I'm having trouble with. I don't want to limit the user to selecting times before midnight to keep everything in the same "daily" cycle so I'd like to be able to logically determine if the users' times are simply within a 24 hour time period and then test that the on time is always less.
Can someone help me work through this? There are so many time and date functions that I really don't know which one(s) I need to do this; plus, I'm unclear on how I should test for this.
I'm starting to think that there is no way to test for this without having a date included. Just the times is not enough.
The time is always within a 24 hour cycle, so if the user puts 01:00/03:00 he's on for 2 hours
If he writes 03:00/01:00 he's on for 22 hours.
I dont see the problem.
The OP wrote in a comment:
The user can opt to get a report
delivered in a window of time. The
user may opt to have their reports
delivered in a window from 23:00:00 to
01:00:00 hours. They may decide
tomorrow that that time is no longer
good and change it to 23:0:00 to
05:00:00 or something like that. Am I
missing something??
You have no problem in the time definition part. You may want to play with the code that sends out the report.
// current time
$timeNow = time();
// fetch user time options from database
$timeOn = [from the database];
$timeOff = [from the database];
// convert times to seconds from epoch
$timeOn = strtotime($timeOn);
$timeOff = strtotime($timeOff);
// if database time is in timestamp format,
// only the hour, minutes and second information is needed
$timeOn = mktime(date("H", $timeOn), date("i", $timeOn), date("s", $timeOn));
$timeOff = mktime(date("H", $timeOff), date("i", $timeOff), date("s", $timeOff));
// if time on is higher than time off, time on is of yesterday
if($timeOn > $timeOff){
$timeOn = strtotime("-24 hour", $timeOn);
}
// decide on report sending
if($timeNow >= $timeOn && $timeNow <= $timeOff){
// Send report
} else {
// Do not send report or reschedule the report
}
Any two times in hh:mm:ss format are going to be within a 24 hour time period, as you state. So unless you actually store a date, I am not sure how you can do this.
If I understand correctly, a start time of 23:00:00 and an end time of 04:00:00 should be acceptable to you (this just means 5 hour work shift)? If this is acceptable, then can you give me an example of unacceptable input?
Perhaps you want to check that the end time is within 12 hours of the start time? That should be feasible.

Categories