I have been trying to figure this out for a week now. My wife has started a new taxi-company and she asked me to code a simple webpage for here where she could press a button to save a timestamp, then the press is again when she gets off work, it then creates a second timestamp
I have an MYSQL database with rows containing the start time and stop time. I have managed to use the diff function to see how much time it is between the two timestamps but now comes the tricky part.
Since it's different payments at different times of the day I need to divide the time at a shortened time.
Up to 19:00 she works "daytime" and after that, she works "nighttime" until 06:00 the other day, then there is "weekend daytime" and "weekend nighttime" as well.
So if she creates a timestamp whit the date and time: 2018-08-08 06:30 and then another timestamp at 2018-08-08 21:00, then I need a script that puts these data in ex "$daytimehours = 12" "$daytimeminutes = 30" and "$nighttimehours = 3" "$nighttimeminutes = 0"
I have managed to create a script that almost works, but it is several pages long, and it contains one if-statement for each different scenario daytime-nighttime, nighttime-daytime etc.
So do anyone has a good idea on how to solve this? or maybe just point me in the right direction. I would be happy to pay some money to get this to work.
My solution is
<?php
date_default_timezone_set('Asia/Almaty');
$endDate = '2018-08-08 21:00';
$startDate = '2018-08-08 06:30';
$nightmare = date('Y-m-d 19:00');
$startDay = date('Y-m-d 06:00');
$diffMorning = strtotime($nightmare) - strtotime($startDate);
$diffNight = strtotime($endDate) - strtotime($nightmare);
echo gmdate('H:i', $diffMorning) . "\n"; // this is the difference from start day till 19:00
echo gmdate('H:i', $diffNight); // this is the difference on nightmare
$total = $diffMorning + $diffNight;
echo intval($total/3600) . " hours \n";
echo $total%3600/60 . " minutes \n";
echo $total%3600%60 . ' seconds';
You can check via online compiler
given two dates stated as:
$endDate = '2018-08-08 21:00';
$startDate = '2018-08-08 06:30';
you can use the PHP Date extension to achieve the difference like this:
$start = date_create($startDate);
$end = date_create($endDate);
$boundnight = clone($end);
$boundnight->setTime(19,00);
$total_duration = date_diff($end,$start);//total duration from start to end
$day_duration = date_diff($boundnight,$start);//daytime duration
$night_duration = date_diff($end,$boundnight);// nighttime duration
you can use the format method to print a human readable string this way:
$total_duration=$total_duration->format('%H:%I');
$day_duration=$day_duration->format('%H:%I');
$night_duration=$night_duration->format('%H:%I');
At this step there is nothing left but you say you want to convert each duration in minutes.So let's build a function :
function toMinute($duration){
return (count($x=explode(':',$duration))==2?($x[0]*60+$x[1]):false);
}
Then you can use it this way:
$total_duration = toMinute($total_duration);
$day_duration = toMinute($day_duration);
$night_duration = toMinute($night_duration);
The output of
var_dump($total_duration,$day_duration,$night_duration) at this step is:
int(870)
int(750)
int(120)
Related
im trying to calculate the time between two different times and output them in hours. It will be displayed to the customer to see how much time the service will take.
Thats my code:
$datetime1 = new DateTime($timeFROM);
$datetime2 = new DateTime($timeTO);
$interval = $datetime2->diff($datetime1);
$hour_decimal = number_format(intval($interval->format('%H')) + round(intval($interval->format('%I')) / 60, 2), 2, '.','');
echo $hour_decimal;
The code works fine for classic jobs, but for work at night its getting complicated because if the second time value ($timeTO) is after 00:00 it calculates from $timeTO to $timeFROM instead of $timeFROM to $timeTO.
Example:
$timeFROM = "6:00";
$timeTO = "8:00";
output = 2.00
That would be correct.
Example 2:
$timeFROM = "23:30";
$timeTO = "1:00";
output = 22.50 And thats wrong. It should be 1.50
Looks like I need to force the function to always calculate from $timeFROM to $timeTO and not the other way around, no matter which value is bigger.
Anyone an idea? Couldn't find anything in google and also didn't know how to ask google for that exactly. Sorry when the solution might be very easy!
Greetings
Add 24 hours if datetime2 is less than datetime1 if you only want forward calculations:
if ($datetime2 < $datetime1) {
$datetime2->add(new DateInterval("PT24H"));
}
In the application that I'm working on, the user must choose a date/time which is at least 5 minutes into the future. For this, I'm trying to implement a check. Below is the code which checks the time difference between the current time and chosen time.
$cur_date = new DateTime();
$cur_date = $cur_date->modify("+1 hours"); //fix the time since its an hour behind
$cur_date = $cur_date->format('m/d/Y g:i A');
$to_time = strtotime($chosen_date);
$from_time = strtotime($cur_date);
echo round(abs($from_time - $to_time) / 60,2). " minute"; //check the time difference
This tells me the time difference from the chosen time and the current time in minutes. So let's say the current time is 09/22/2015 5:53 PM and the chosen time is 09/22/2015 5:41 PM - it will tell me the difference which is 12 minutes.
What I want to know is how I can tell if those 12 minutes are into the future or in the past. I want my application to only proceed if the chosen time is at least 5 minutes into the future.
You're doing too much work. Just use DateTime() to do the date math for you:
// Wrong way to do this. Work with timezones instead
$cur_date = (new DateTime()->modify("+1 hours"));
// Assuming acceptable format for $chosen_date
$to_time = new DateTime($chosen_date);
$diff = $cur_date->diff($to_time);
if ($diff->format('%R') === '-') {
// in the past
}
echo $diff->format('%i') . ' minutes';
Demo
$enteredDate = new DateTime($chosen_date)->getTimestamp();
$now = new DateTime()->getTimestamp();
if(($enteredDate-$now)/60 >=5)echo 'ok';
Basically, the code takes the two dates converted in seconds since 1/1/1970. We calculate the difference between the two dates and divide the result by 60 as we want minutes. If there is a difference of at least 5 minutes, we're ok. If the number is negative, then we are in the past.
If anyone is looking to do something similar, I found the Carbon library which is included by default with the framework I am using (Laravel 5), it was much easier to do this calculation.
$chosen_date = new Carbon($chosen_date, 'Europe/London');
$whitelist_date = Carbon::now('Europe/London');
$whitelist_date->addMinutes(10);
echo "Chosen date must be after this date: ".$whitelist_date ."</br>";
echo "Chosen Date: ".$chosen_date ."</br>";
if ($chosen_date->gt($whitelist_date)) {
echo "proceed";
} else {
echo "dont proceed";
}
I made some code that works, but it seems very inefficient. I am charting circles on a canvas to show when events happen during a work day. To do this I find the number of seconds of the day this happened, then convert this to minutes to show.
My question is why do I have to go strtotime(date('...',strtotime(time))) and call strtotime twice?
When I just had it like strtotime(date('Y-m-d',time) I would get a negative value.
<?php
$time_concerned = '2014-10-31 02:00:00';
$start_day_temp = strtotime(date('Y-m-d',strtotime($time_concerned)));
$end_day_temp = strtotime(date('Y-m-d H:i',strtotime($time_concerned)));
$num_seconds = $end_day_temp - $start_day_temp;
//divide by 60 to get minutes. divide in half to make fit on 720 scale.
$num_conv_minutes = (($num_seconds/60)/2);
echo ' ctx.fillStyle = "#00FF00";';
echo ' ctx.beginPath();';
echo ' ctx.arc('.$num_conv_minutes.'+ x_inbound,y_truck_arrivals,5,0,2*Math.PI);';
echo ' ctx.fill();';
echo ' ctx.stroke();';
?>
$time_concerned = '2014-10-31 02:00:00';
echo strtotime(date('Y-m-d',strtotime($time_concerned)));
echo "\r\n";
echo strtotime($time_concerned);
Try this. Fiddle.
These are almost the same thing. The only reason they're different is because when you convert the string to a date you're dropping the second minutes and hours, so PHP puts it to midnight and you lose the part that tells you you did all this at 2am.
This is useful the first time you use it because you need to get the timestamp of midnight to subtract from the other timestamp. However, the second time it's just redundant.
So here's how you do it..
$time_concerned = '2014-10-31 02:00:00';
$start_day_temp = strtotime(date('Y-m-d',strtotime($time_concerned)));
$end_day_temp = strtotime($time_concerned);
I've been trying at this for a bit and can't get the damn code to work.. This is my first post, I've gone through a few, tried a million different ways.. I just want to get the difference in hours, then I'm set, I'll get the rest figured out..
Right now, it's giving me unusual answers (say there's a 2 hour difference, it'll give me 14 as an answer) Pardon my coding, I haven't done this in years and have no real formal training. I'll be as thorough as possible in my comments, and thanks a LOT. Any links appreciated. I have tried a LOT. Using PHP 5.3.something, and am pulling off a Wordpress 3.7.1 database.
Thanks in advance for the help for a beginner. I want to display "Updated x hours ago". Once I have the darned thing displaying the correct result, I'll figure the rest out.
//This is the current date, putting it into strtotime so everything is in the same format. It displays accurately.
$currentDate = date("Y-m-d");
$currentTime = date("H:i:s");
$currentDateHour = date("H", strtotime($currentDate . $currentTime));
// This is the date I'm pulling from the database, it only displays
// when in strtotime for some reason. It displays accurately to what is in the mySQL DB
$upDate = date("Y-m-d H", strtotime($row2[post_date]));
// Some variables to make life easier for later if statements if I ever get that far. Displays accurately.
$upDatehour = date("H", strtotime($row2[post_date]));
// trying simple subtraction
$hour = $currentDateHour - upDatehour;
// this is where the result is incorrect, what is wrong here? Any method I've tried gives me the same result, with or without strotime.. it's gotta be something simple, always is!
print strtotime($hour);
You can drastically simplify your code. I'd recommend refactoring it to use DateTime and specifically DateTime::diff().
$now = new DateTime();
$post = new DateTime($row2['post_date']);
$interval = $now->diff($post);
echo "Updated " . $interval->h . " hours ago";
Working example: http://3v4l.org/23AL6
Note that this will only show up to 24 hours difference. If you want to show all hours even for a difference of more than 24 hours, you'll need to figure in the days. Something like this:
$hours = $interval->h + ($interval->format("%a") * 24);
echo "Updated $hours hours ago";
Working example: http://3v4l.org/ilItU
If you are just trying to get the number of hours between two arbitrary times, the easiest way would be to get the difference in seconds of the two times, and then divide by 3600 to determine the number of hours between the two dates.
Here is a basic example:
<?php
$row2['post_date'] = '2013-12-02 07:45:38'; // date from database
$now = time(); // get current timestamp in seconds
$upDate = strtotime($row2['post_date']); // convert date string to timestamp
$diff = $now - $upDate; // subtract difference between the two times
$hours = floor($diff / 3600); // get the number of hours passed between the 2 times
echo $hours; // display result
Also, Wordpress has a built in function that may end up doing what your ultimate goal is, see wordpress function human_time_diff().
Example:
<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago';
Result:
2 days ago.
Example how to get difference between dates in hours:
$diff = date_diff(date_create(), date_create($row2['post_date']));
$hours = $diff->days * 24 + $diff->h;
If you wish to format output number with leading zeros, you can use sprintf() or str_pad() function. Example of sprintf() use for HH:mm format:
echo sprintf('%02d:%02d', $hours, $diff->i);
demo
I have a date value stored in a variable. I need to extract the time part of the value in to a separate variable and then add/subtract time from it.
The date variable is set with date('YmdHis'), giving (for example) 20110805124000 for August 5th 2011, 12:40:00
From the value 20110805124000 (which is stored in the variable $fulltime), I need to store the time only in the format 12:40 (so ignoring the year, month, day and seconds and adding the colon between the hour and minute) in a variable called $shorttime. I then need to add a number of hours to that time (so for example +3 hours would change the value in the $shorttime variable to 15:40). The number of hours I need to add is stored in a variable called $addtime, and this value could be a negative number.
Is this easily doable? Could anyone help?
Thanks :)
$time = '2013-01-22 10:45:45';
echo $time = date("H:i:s",strtotime($time));
It will give the time 10:45:45 from datetime.
<?PHP
$addhours = 3;
$date = DateTime::createFromFormat('YmdHis', '20110805124000');
$shorttime = $date->format("H:i");
$newdate = $date->add(DateInterval::createFromDateString($addhours . "hours"));
$newtime = $newdate->format("H:i");
echo $shorttime . "<br />";
echo $newtime . "<br />";
?>
for your reference:
http://www.php.net/manual/en/datetime.createfromformat.php
http://www.php.net/manual/en/dateinterval.createfromdatestring.php
hello the way I usually do it is like this, maybe it's a bit long but it works for me...
$DateIn = new DateTime($In);
$DateOut = new DateTime($Out);
$HourOut = new DateTime($H_Out);
$FechaEntrada = $DateIn->format('d-m-Y');
$FechaSalida = $DateOut->format('d-m-Y');
$HoraSalida = $HourOut->format('H:i a');
the guide I used was the PHP one DateTime::format()