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);
Related
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.
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'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
How can I compute time difference in PHP?
example: 2:00 and 3:30.
I want to convert the time to seconds then subtract them then convert it back to hours and minutes to know the difference. Is there an easier way to get the difference?
Look at the PHP DateTime object.
$dateA = new DateTime('2:00');
$dateB = new DateTime('3:00');
$difference = $dateA->diff($dateB);
(assuming you have >= PHP 5.3)
You can also do it the procedural way...
$dateA = strtotime('2:00');
$dateB = strtotime('3:00');
$difference = $dateB - $dateA;
See it on CodePad.org.
You can get the hour offset like so...
$hours = $difference / 3600;
If you are dealing with times that fall between a 24 hour period (0:00 - 23:59), you could also do...
$hours = (int) date('g', $difference);
Though that is probably too inflexible to be worth implementing.
Check this link ...
http://www.onlineconversion.com/days_between_advanced.htm
I used this to calculate the difference between server time and the users local time. Grab the hour difference and drop that in a form when the user is registering. I then use it to update the time on the site for the user when they do stuff online.
Once I got it working, I switched this line ...
if (form.date1.value == "")
form.date1.value = s;
to ...
form.date1.value = "<?PHP echo date("m/d/Y H:i:s", time()) ?>";
Now I can compare the user time and the server time! You can grab the seconds and mins as well.