What's wrong with my code? I want my script to check if it is Monday and is greater or equal to 22:00 and less than or equal to 23:00.
$t = date("D:G:i");
if ($t >= "Mon:22:00" && $t <= "Mon:23:00") {
$status = "up";
} else {
$status = "down";
}
you cannot compare strings (it is not dates, it is just strings of arbitrary symbols), as we're not code-writing monkeys I'll just describe how you should do it instead of providing copy-pastable code:
get weekday number, hour, minute from current time into 3 separate variables
compare weekday variable with monday value
if weekdays are ok - compare hours with 22
minutes can be omitted here, if you check for [22, 23), or you need to make additional comparison for 23:00 case
another approach - generate unix timestamps for the closest monday 22 and 23 hours, and then numeric comparisons
You're comparing two strings instead of two numerical values. Not ideal at all. You want to look into converting the dates into a Unix timestamp and comparing those values.
mktime: http://php.net/manual/en/function.mktime.php
mktime will allow you to get a Unix timestamp for any date.
time: http://php.net/manual/en/function.time.php
time will give you the current date and time as a Unix timestamp.
You can then compare to find out which is larger/smaller than the other.
Related
I want to display content from the database with dates up to 2hours ahead of time.
Example:
2018-11-09 20:00:00.000000
2018-11-08 19:00:00.000000
2018-11-06 19:00:00.000000
2018-11-06 18:00:00.000000
Lets say the time and date is
Nov 6th at 6pm. I want the bottom two entries to be displayed and the two future dates to not show until the current time is within 2hours of that time.
My code is as follows:
$cT = strtotime($row3['MissionTime']) - strtotime("now");
if($cT <= strtotime('-2 hours')) {
echo $row3['MissionTime']."<br>";
}
I've tried several different ways but I can't seem to get this to work right. Help and tips?
The reason your code doesn't work is that strtotime returns a number of seconds since the unix epoch. When you subtract two results of strtotime you will get a number of seconds difference which is as you expect. However you cannot compare that value to strtotime('-2 hours') as the output of that will be the timestamp for 2 hours before now (which right now is 1541539906), so the test will always pass. You should just compare it to 7200 instead (I'm pretty sure based on your question description that +7200 is more appropriate than -7200). so change
if($cT <= strtotime('-2 hours')) {
to
if($cT <= 7200) {
Note that it is almost certainly better to do this in your query. Try adding a condition on your time column as something like
WHERE MissionTime <= NOW() + INTERVAL 2 HOUR
And then you won't need to check in the PHP at all.
strtotime() returns a timestamp in seconds. Subtracting two timestamps gives you a difference between those two timestamps, in seconds.
So if strtotime($row3['MissionTime']) is a timestamp that's 1.5 hours in the future, and you subtract strtotime("now") from it, you end up with a difference of 5400 seconds (60 seconds * 60 minutes * 1.5 hours).
strtotime('-2 hours') gives you the timestamp for 2 hours ago, which is currently somewhere around 1.5 billion. This is not very useful for your situation.
Here are two ways to modify your code:
$cT = strtotime($row3['MissionTime']) - strtotime("now");
if($cT <= 7200) {
echo $row3['MissionTime']."<br>";
}
If the difference between $row['MissionTime'] and now is less than 7200 seconds (60 seconds * 60 minutes * two hours), $row3['MissionTime'] is either in the past or it's within the next two hours.
Alternatively:
if(strtotime($row3['MissionTime']) <= strtotime('+2 hours')) {
echo $row3['MissionTime']."<br>";
}
Basically the same, but perhaps more readable if you're not planning to use $cT for anything else. This simply checks if $row3['MissionTime'] is earlier than whatever time it will be in +2 hours.
I have a date range that comes from MySQL, for example:
2016-01-05 to 2016-01-10. I would like to check if both Saturday and Sunday are inside that date-range, not necessarily consecutive. So far I have found:
function isWeekend($date) {
return (date('N', strtotime($date)) >= 6);
}
So I would have to loop for every single day in the range to see if it's a weekend day.
Are there any better approaches?
You don't need to loop over all the days. You just need to know the length of the date range and the first day's day of the week.
Assuming you have two DateTime objects:
$start = new DateTime('2016-01-05');
$end = new DateTime('2016-01-10');
You can determine if a Saturday and Sunday are contained in the date range by checking if the length of the range plus the numeric weekday of the start date is greater than 6.
function includes_weekend (DateTime $start, DateTime $end) {
return $start->diff($end)->format('%a') + $start->format('w') > 6;
}
format('%a') returns the total number of days in the DateInterval returned by diff, and format('w') returns the numeric day of the week (Sunday = 0).
You would not have to check every single day.
I'll try to explain this with just plain English:
First, check if it starts on a weekend. If it does, you're already done. If the date span is more than 6 days, then you can immediately assume that yes, a weekend day is included. If it's 5 days, then the first day has to be on a Monday, otherwise it contains a weekend day. If it's four, it has to be on a Tuesday... and so on.
I'm looking for an easy way to see if more than two hours has passed between two dates. I can either do this with a MySQL DATETIME value, or if needed, I can convert that to a UNIX timestamp. I just need an easy way to to compare those two dates and see if more than 2 hours has passed.
try to look into DATEDIFF function in MySQL.
A UNIX timestamp is just the number of seconds that have elapsed since 12:00AM UTC, January 1, 1970.
Two hours in seconds is 60 * 60 * 2 = 7200. So,
if($secondTimestamp - $firstTimestamp >= 7200)
{
echo '2 hours have elapsed.';
}
Since you tagged with php, you could use PHP's DateTime::diff (DateTime::diff) to get a diff between two datetime objects. I guess it depends on where in your application you are doing the comparison.
In PHP
$time = strtotime($date2) - strtotime($date1); //this will give difference in seconds between two dates
if(($time/3600) >= 2) { // 2 hours has left }
Hello i am learning php i tried to use the date function to display the current time.
I have an if statement to check the current time whether it is greater than the next hour.
Here is the code
<?
$current_time= date('G:i:s');
$next_time= date('G:i:s',strtotime('+1hour'));
if($current_time > $next_time )
{
echo $current_time." is greater than ".$next_time;
}
?>
At the time of writing this code it was 9:23:39
and the next hour should have been 10:23:39
Surprisingly i got :
9:23:39 is greater than 10:23:39
Am i missing something here.
Please help
Keep in mind you are comparing strings, not numbers. 9 is greater than 1 and therefore returns true.
Either use the DateTime class to do this, or compare the unix timestamps (time() and strtotime('+1hour'))
you could use a integer to work the if statement
$var = date("U",timestamp)
to get the number of Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) thus giving you a number which you can determine which one is greater.
i have to sent an email when a user register email contain a link that is become invalid after six hours
what i m doing when email is sent i update the db with field emailSentDate of type "datetime"
now i got the curent date and time and has made to the same formate as it is in db now i want to find that both these dates and time have differenc of 6 hours or not so that i can make link invalid but i donot know how to do this
my code is look like this i m using hardcoded value for db just for example
$current_date_time=date("Y-m-d h:i:s");
$current=explode(" ",$current_date_time);
$current_date=$current[0];
$current_time=$current[1];
$db_date_time="2010-07-30 13:11:50";
$db=explode(" ",$db_date_time);
$db_date=$db[0];
$db_time=$db[1];
i do not know how to proceed plz help
<?php
//$now = new DateTime(); // current date/time
$now = new DateTime("2010-07-28 01:11:50");
$ref = new DateTime("2010-07-30 05:56:40");
$diff = $now->diff($ref);
printf('%d days, %d hours, %d minutes', $diff->d, $diff->h, $diff->i);
prints 2 days, 4 hours, 44 minutes
see http://docs.php.net/datetime.diff
edit: But you could also shift the problem more to the database side, e.g. by storing the expiration date/time in the table and then do a query like
... WHERE key='7gedufgweufg' AND expires<Now()
Many rdbms have reasonable/good support for date/time arithmetic.
What you can do is convert both of your dates to Unix epoch times, that is, the equivalent number of seconds since midnight on the 31st of December 1969. From that you can easily deduce the amount of time elapsed between the two dates. To do this you can either use mktime() or strtotime()
All the best.
$hoursDiff = ( time() - strtotime("2010-07-30 13:11:50") )/(60 * 60);
I'd rather work with a timestamp: Save the value which is returned by "time()" as "savedTime" to your database (that's a timestamp in seconds). Subtract that number from "time()" when you check for your six hours.
if ((time() - savedTime) > 6 * 3600)
// more than 6h ago
or
"SELECT FROM table WHERE savedTime < " . (time() - 6 * 3600)
This might be the solution to your problem -> How to calculate the difference between two dates using PHP?