Does date fall within 7 days? PHP - php

Is there a way to find out if a date falls within 7 days of the current date using PHP? If there is, would it also be possible to figure out how many days away that date is?

$date = strtotime('2010-11-28');
if (strtotime('-7 days') < $date && $date < strtotime('+7 days')) {
// yup
}
$difference = abs($date - time()) / 60 / 60 / 24;
Could be refined a bit if you care about edge cases, whole days and daylight-savings/leap seconds issues, but this should hopefully give you the right idea. Of course the Date class should be the preferred method to handle this, but it's only available in PHP 5.3+.

For the first one, add 7 days to the current date and see which is greater.
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add
For the second one:
http://php.net/manual/en/function.date-diff.php

Related

Display Database Entities within a specific time frame

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.

PHP - Parsing String As Past Date

Currently, I'm trying to parse out dates when messages were received into timestamps. I have the month and day but the year is not specified. The event always occurs at the most recent (human) reading of the time. It works great in most cases to do this:
$time = strtotime("Jan 2 8:38pm");
That returns a date for this year, which is correct. Unfortunately, I get problems when I try to do for example:
$time = strtotime("Dec 31 8:38pm");
That returns a date which hasn't happened yet, and wont happen for the whole rest of the year. Obviously, my message was not sent in the future. I need it to return December 31st of last year.
For weekdays, I had a solution by prepending 'last' before the weekday like so:
$time = strtotime("Last Saturday 8:38pm");
That always returned the time of the last Saturday. However, trying to do the same thing here doesn't work:
$time = strtotime("Last Dec 31 8:38pm");
This returns false. I know to decrement a date by 1 year, I can do this:
$time = strtotime("Dec 31 8:38pm -1 year");
And that works great for Dec 31. However, Jan 2 will now fail:
$time = strtotime("Jan 2 8:38pm -1 year");
One solution I thought of was to subtract off a year (86400 * 365) from the resulting value if it is past today's date. However, this result will fail if we passed over February of a leap year. In that case, we would end up with a time that was ahead by a day.
The best solution I came up with so far is this:
$time = strtotime($raw_time);
if ($time > time()) {
$time = strtotime($raw_time." -1 year");
}
It seems kind of wasteful to make two calls to strtotime which I know is probably not a very efficient function. Is this the most elegant solution?
Is anyone aware of an option in strtotime which forces the dates to be in the past instead of in the future?
Is there another way to parse these dates that I should consider?
Efficiency is important for this because I am going to be parsing a lot of dates with it, but I would also like simple and readable code so I can understand it later.
Your approach is fine, as there is no date format to get what you want. Another approach could be using the DateTime class:
$datetime = new DateTime($raw_time);
if ($datetime > new DateTime()) {
$datetime->modify('-1 year');
}
You could test which one of the two approaches is faster. My guess is that this is a micro-optimization that won't make a lot of difference.

Check if more than two hours has passed

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 }

PHP error when using strtotime

Hi I get an error when trying to get date interval using php strtotime function
the code is:
<?php
$interval = time() - strtotime('1992/08/13');
//expect to be 18
// but the output is 1988
print date('Y', $interval);
?>
any advice?
thanks
If you want to deal with date intervals in PHP I can't recommend the DateInterval class enough. I wrote a blog post on this earlier this week: Working with Date and Time in PHP
There's an example of using it there that should allow you to do what you want to do.
That is because all time() functions are seconds since epoch which is in 1970, so your out is actually 18 years since epoch. If you want it to get the difference in years you will probably have to calculate the difference yourself.
print $interval / (60*60*24*365.242199);
Are you tring to get the years elapsed rather than the actual year?
If so:
$year = 31556926;
$interval = time() - strtotime('1992/08/13');
print round($interval / $year);
$interval = time() - strtotime('1992/08/13');
These PHP functions deal with UNIX timestamps. That means the number of seconds from 1970. 01. 01. So 1992/08/13 is transformed into a timestamp (seconds). time() gives the current timestamp (seconds). You subtract the former from the latter, and you get the amount of seconds between those two dates. This is not a date itself, just an interval.
If you want to get the year, do something like echo $interval/(60*60*24*365); which will convert your seconds to years (not accurate, leap years will not be taken into consideration). Though your best option is checking out #James C's link and use his solutions. I just wanted to give some explanation.

Dates difference with php

Hi guys I was wondering if anyone could help me with the following:
I have two dates entered in two different fields > startDate and endDate.
As they are entered I would like to show a warning if:
the second one is a date before the first one. So it is wrong.
and that between the first one and the second one there a minimum gap of at least 3 days during certain period of the year and 7 days during other periods of the year.
I was thinking to write a PHP function but how do I call it as soon as the second date is entered?
Many many thank for you help
Francesco
Convert your dates to Julian day with gregoriantojd.
/**
* Get the Julian day of a date. The Julian day is the number of days since
* January 1, 4713 BC.
*/
function datetojd($date)
{
return gregoriantojd(idate('m', $date),
idate('d', $date),
idate('Y', $date));
}
// you can use strtotime to parse a lot of date formats, assuming they are text
$startDate = strtotime('22nd Nov 2009');
$finishDate = strtotime('26nd Nov 2009');
$diff = datetojd($finishDate) - datetojd($startDate);
if ($diff < 0) {
// oops, $finishDate is before $startDate
}
else {
// check $diff is at least 3 or 7 depending on the dates
}
Do the check on the client side with Javascript.
Then perform the same checks server side which can present a message after the form has been submitted (for those few users running with Javascript disabled?).
I'm not sure if you can call it as soon as the second date is entered, unless you reload the page or have the function on another page which could get a tad complicated
The way i would check the dates is to use php's mktime function, which will give you the unix time. Then if the second one is less that the first, the second date is before and if the second one is less that the first + 3 * 24 *60 * 60 (seconds in 3 days) then it isn't 3 days apart
1° case:
SELECT [whatever you need from the table] WHERE endDate < startDate
2°case:
SELECT [whatever you need from the table] WHERE (endDate - startDate) >= IF([select that define in wich period of the year the data are],3, 7)
This ill do the trick, but probably your problem cant be solved sql-side.
Please, describe better what you need to do.
EDIT:
Ok, then as someone else suggested, first check htem by js (for convenience, not for safely: never rely only on js validation!)
Use strtotime for the comparison/operation.
EDIT2 (last;) :
Go with Alex's Answer

Categories