The date string looks like this
2011-08-19 17:14:40
(year-month-day hours:minutes:seconds)
How can I find out if the date is older than the current date with more than 30 days?
Join Stack Overflow to learn, share knowledge, and build your career.
Try using something like this:
if(strtotime('2011-08-19 17:14:40') < strtotime('-30 days')) {
// this is true
}
Besides, this string looks like it is stored in SQL as datetime/timestamp field. You can directly select all entries from your database with old dates using:
SELECT ... WHERE `datetime` + INTERVAL 30 DAY < NOW()
If you are on PHP 5.3 or higher you can do:
$someDate = new \DateTime('2011-08-19 17:14:40');
$now = new \DateTime();
if($someDate->diff($now)->days > 30) {
echo 'The date was more than 30 days ago.';
}
h
property for 'hours' but it is actually a fragment of the difference (as it relates to y (years), m (months), d (days), etc). To get hours, I'd do ($now->getTimestamp() - $someDate->getTimestamp()) / 3600
. This would return a decimal. You could then optionally use round(), intval(), etc. if you want it as an integer.
– Collin Krawll
Jul 28 '17 at 16:21
diff
method looks very elegant.
– cezar
Feb 17 '19 at 12:23
You can use Carbon as follows
if (30 - ((new \Carbon\Carbon($given_date, 'UTC'))->diffInDays()) < 0) {
echo "The date is older than 30 days";
}
strtotime('2011-08-19 17:14:40') + 30 * 24 * 60 * 60 < time();
strtotime('2011-08-19 17:14:40') + 30 * 24 * 60 * 60 < time();
correct it.
– nobody
Aug 20 '11 at 8:58
24 * 60 * 60
calculations, because they can become inaccurate when dealing with things like daylight savings time. It's better to use something like RiaD suggests, and let strtotime()
handle the relative time calculations.
– AgentConundrum
Aug 20 '11 at 9:02
30 * 24 * 60 * 60
is always exactly 30 days
no matter where in the universe you are.
– nobody
Aug 20 '11 at 9:08
With the meringue library, this can be done in at least two ways.
The first one looks like the following:
(new Future(
new DateTimeParsedFromISO8601String('2011-08-19 17:14:40'),
new NDays(30)
))
->earlierThan(
new Now()
);
The semantics is the following: first, you parse a date from an ISO8601 string, then create a future date which is thirty days later than that, and finally compare it with current datetime, that is, now
.
The second way is creating an interval from a datetime range and counting the days it consists of. It looks like that:
(new TotalFullDays(
new FromRange(
new FromISO8601('2011-08-19 17:14:40'),
new Now()
)
))
->value();
Both approaches are quite intuitive and don't make you remember special php datetime expressions. Instead, every implementation is autocompleted; you just need to build a correct object that suits your needs.