Aipo
Aipo

Reputation: 1985

How to calculate duration in days?

I have to make a notification after 30 days.

foreach ($pdo->query($sql) as $row) {
$date = date_create($row['data']);
$laikotarpas = date_diff(new DateTime("now"), $date);
// var_dump($liko);
$liko = 30 - $laikotarpas->d;

I want correct result in days. I have added a row at 2014.03.19 and this shows that left 3days to 30.

My goal is to achieve: I add record at 2014.03.19 and get result how many days have passed from today. I thought that $laikotarpas->d gives a duration in days, but, when i do calculations to set the limit for 30days. So my main problem is to get correct $liko, but I have no idea how. I am adding my time using this code (using PDO):

$q->execute(array($name, 
date("Y-m-d H:i:s", time())
);

In my database I use DATETIME. And i print that date from SQL using this php:

<?php echo date_format(date_create($data['data']), 'Y-m-d'); ?>

Is my way good? How to improve this?

-----edit-----

I have to use php5.2

Just got an idea, it takes only days and ignores months passed count. How to update that to count duration only in days?

Upvotes: 1

Views: 945

Answers (2)

scrowler
scrowler

Reputation: 24406

If you want to find the difference between now and a date in the past, try something like this:

PHP >= 5.2.0

$then = '2014-03-19';
$date = new DateTime($then);
$now = new DateTime('now');
$diff = $date->diff($now);

echo $diff->days . ' days since ' . $then . PHP_EOL; // 58 days since 2014-03-19

PHP < 5.2.0

$date = strtotime($then);
$now = time();
$diff = $now - $date;
$days = round($diff / 60 / 60 / 24); // convert seconds to days and round off

Note: after understanding more about your problem, I highly suggest you filter your results based on date ranges in MySQL rather than PHP - it'll be easier and more economic and will reduce your potential risk for affecting data you didn't mean to. See Cull Larson's answer.

Upvotes: 3

Cully
Cully

Reputation: 6965

You could just use a query like this:

SELECT * FROM myTable WHERE DATE(signupDate) = DATE_SUB(NOW(), INTERVAL 25 DAY);

That will give you all results with a signup date that is 25 days old. If you have a flag in the table telling you whether you've notified them, you can pass that along too:

SELECT * FROM myTable WHERE notified=false AND DATE(signupDate) = DATE_SUB(NOW(), INTERVAL 25 DAY);

If you want to get every record 25 days or older, that hasn't been notified:

SELECT * FROM myTable WHERE notified=false AND DATE(signupDate) <= DATE_SUB(NOW(), INTERVAL 25 DAY);

Upvotes: 2

Related Questions