M. Koning
M. Koning

Reputation: 11

How do i compare dates with a value? PHP

I am currently working on a project. I'm suposed to compare a date from my database and the curent date. If the curent date is bigger than the date from the database i am suposed to cound how many times the duration of the item fits in the database date till its bigger than the curent date.

All i got is the curent date, the duration of the item and the date in the database.

What i did befor was use this while loop:

while(date('Y-m-d') > $value->start) {
    $value->start= date('Y-m-d', strtotime("+" . $value->contractDuration . " months", strtotime($value->start)));
};

But i'm not allowed to use a while loop. Any clue how to get the same result?

Upvotes: 0

Views: 72

Answers (3)

user3106619
user3106619

Reputation: 11

$start=$value->start; $contractDuration=$value->contractDuration; try below code.

$start = '2018-04-09';
$contractDuration = 1;
$contractDurationDate = strtotime("-" . $contractDuration . " months");
$now=strtotime(date('Y-m-d'));
$start=strtotime($start);
if ($contractDurationDate < $now && $start< $now) {
    echo 'Contract duration is active';
} else {
    echo 'Contract Expired';
}

Upvotes: 1

IsThisJavascript
IsThisJavascript

Reputation: 1716

I quite like using DateTime and the use of date_diff for this:

<?php

$databaseDate = new DateTime("2018-01-02");
$today = new DateTime();

if($today > $databaseDate){
    echo date_diff($today, $databaseDate)->format("%a")." days";

}

Will output 160 days.

https://3v4l.org/3FfKp

If you want months, replace %a with %m

Upvotes: 0

sree
sree

Reputation: 389

Try with below code. It might help you

$now = time();
$target = strtotime($date_from_db);
$diff = $now - $target;
if ( $diff > 900 ) {
  // something
}

or, more succinctly:

if( time() - strtotime($date_from_db) > 900 ) {
  // something
}

Upvotes: 0

Related Questions