I need get the range by hours starting of the acctually hour, example: If in this moment are at 05:25, i need get 05:00 and 06:00.
I have this code:
$currentHour = (new DateTime())->format('H:00');
$nextHour = (new DateTime('+59 minutes'))->format('H:00');
$timeRangeFinal = [$currentHour, $nextHour];
If the present hour not is 01:00, 02:00, 03:00... the code work fine, but if the present hour is for example 02:00, the array is same, $timeRangeFinal[0] = "02:00" and $timeRangeFinal[1] = "02:00".
How can i get the range by a hour with *:00?
You need to change this line of code
$nextHour = (new DateTime('+59 minutes'))->format('H:00');
to this
$nextHour = ((new DateTime())->modify('+1 hour'))->format('H:00');
i have written a little bit for you. this is a way to do it but it it is in the way you are adding 1 hour on top of it.
i have written a small selution (this also helps me learing so i am happy to do it).
$currenttime = new \DateTime();
$currenttimehour = $currenttime->format('H:00');
$nextHour = $currenttime->add(new DateInterval('PT1H'))->format('H:00');
echo $currenttimehour;
echo ' ';
echo $nextHour;
this is going from the current time. it first format's it to the hour you are in. next it wil add the 1 hour extra you need and format it to the correct format.
i hope i could be of some help to you.
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"));
}
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)
So I have a database which stores a date-time value. I want to find out if the date is in the past - I don't care about the time part in this instance, just the date.
So I have the following code at the moment
//this is the current date
$today = strtotime(date("Y-m-d"));
//this is the date from the database
$gameDate = strtotime($rec[0])
if (strtotime($rec[0]) < $today) {
I feel like I am not doing this in the most accepted way, but my brain hurts from too much data and I was hoping someone could give me a pointer as to the 'correct'approach.
Assuming you only care about the Date part, and not the time part, as in 2016-01-01 14:00:00 and 2016-01-01 15:00:00 would be counted as the same day and not the past, you can use the following:
$dateFromDatabase = new DateTime('2016-05-23 17:00:00'); // $rec[0] in your case
$current = new DateTime();
$difference = $current->diff($dateFromDatabase);
if ($difference->format('%R') === '-') {
echo 'Date is in the past';
}
ideone can be found here
Any issues let me know.
One thing that has always confused me is Time in coding. I am very confused on how to go about doing this! Simply, I have a MySql Timestamp, and I want to subtract that from 24 hours.
Basically, I am trying to code something that only lets you complete an action once every 24 hours, and then if they try to complete it more then once it will tell them how long they have to wait to do it again.
This is the code I currently have:
$dailylogincheck = 2015-08-16 13:30:32 //MySQL Timestamp
date_default_timezone_set("America/New_York");
$lastloginbonus = new DateTime($dailylogincheck);
$currenttime = $lastloginbonus->diff(new DateTime(date("Y-m-d H:i:s")));
I don't have to use this code (if there is a better way to do this). So I would just like to subtract the current Timestamp from 24 hours, but I have no clue how to do this in PHP :( Please Help!
P.S. I would simply like to display a sentence like the following: You have already done this within the past 24 hours. Please come back in X hours X minutes and try again.
hope this works :-)
<?php
$dailylogincheck = '2015-08-16 13:30:32';
$end = new DateTime($dailylogincheck);
$end->add(new DateInterval('P1D'));//add 1 day to find end date
$now = new DateTime('now');
$interval = $end->diff($now);
if($end->diff($now)->days >= 1){
echo 'go for it';
}else{
echo $interval->format('%H hours, %i minutes until you can XXX');
}
As Dagon said, doing it in mysql is the best approach... but to address your php question, DateTime will accept a number of simple modifiers:
<?php
$lastBonus = new DateTime("-1 day"); // Last bonus was exactly 24 hours ago
$canNotGetNewBonus = new DateTime("-1 hour"); // Attempting another bonus 23 hours later
$canGetNewBonus = new DateTime("+1 hour"); // Attempting another bonus 25 hours later
var_dump($lastBonus->diff($canNotGetNewBonus)->days >= 1);
var_dump($lastBonus->diff($canGetNewBonus)->days >= 1);
I've been doing a good amount of research with this, and used a few codes to get to know how to make this work, but nothing has worked the way I wanted it to, or hasn't worked at all.
The code is:
<?php
$time1 = $user['last_active'];
$time2 = "+5 minutes";
if (strtotime($time1) > strtotime($time2)) {
echo "Online!";
}else{
echo "Offline!";
}
?>
It is supposed to compare the two variables, and find out if the last active variable is greater or less than 5 minutes, and if it is greater, appear offline. I do not know what's wrong as the NOW() updates on each page and stops if the user is not logged in. Any suggestions or help? Thanks.
The $time1 variable is coming from a fetched array that gets the ['last_active'] information that updates on each page.
I fixed my code, but it still doesn't work right, however, I think I have managed to get further than I was..
<?php
$first = new DateTime();
$second = new DateTime($user['last_active']);
$diff = $first->diff( $second );
$diff->format( '%H:%I:%S' );
if($diff->format( '%H:%I:%S' ) > (strtotime("5 minutes"))){
echo "Offline";
}else{
echo "Online";
}
?>
What can I do at this point?
Nobody pointed out that you actually have a bug. The "current time" will never be greater than "the current time +5 minutes"
Your first code sample will work right if you instead use "-5 minutes" as the "online threshold."
Also, comparing a timestamp without date to the output of strtotime() as you do in the second code is not a proper comparison. It has two problems:
Each time a new day comes around, the same time value will be repeated.
The output of strtotime is an integer representing seconds-since-epoch; the output of format() is a textual representation of hours:minutes:seconds within the current date.
As for your question how to calculate time between 2 dates / time, please view the solution on the following posts, that should give you enough information! (duplicate ? )
Calculate elapsed time in php
And here
How to get time difference in minutes in PHP
EDIT AS YOU PLEASE
<?
$first = new DateTime(); // this would hold your [last active]
//$first->modify("-6 minutes");
$second = new DateTime("NOW");
$difference = $second->diff( $first ); // second diff first
if ($difference->format('%i') > 5) { // comparing minutes only in example ( %i )
echo "The user is AFK";
} else {
echo "user might still be active";
}
?>