Jump to content

Getting difference between 2 dates


Go to solution Solved by mac_gyver,

Recommended Posts

Hi,

I have this code that I am trying to check between 2 dates. the first date taken from DB abd the second date is currect date. I want to compare between them (how many days left, it is not working.

 

<?php
        include('connect.php');
        $sqlSelect = "select dueDate as date from subscriptions";
        $result = mysqli_query($conn,$sqlSelect);

        $date = new DateTime(date('d-m-Y H:i:s'));

        while($data = mysqli_fetch_array($result))
        {
            $diff=date_diff($date,$data["date"]);
            if( $data["date"] > $date && $diff < 15) 
            {
                  print("ok");
            }
        }
?>

How to go about this?

Link to comment
https://forums.phpfreaks.com/topic/327414-getting-difference-between-2-dates/
Share on other sites

  • Solution

you should do this directly in the sql query statement. MySql has a large number of datetime functions. what is the format of the 'date' column in the database table?

if you do this in the php code, you must either compare objects with objects or compare formatted strings with formatted strings, with the same exact format, in a left-right order from most significant field (year) to least significant field (day.)

the current php code produces a fatal error at the date_diff() method call, because the 2nd argument must be an object, not the $data["date"] string.

$date is a datetime object, you cannot directly compare it with the $data["date"] string. you either must use the datetime ->format() method to produce a formatted string from the $date object, or you must create a datetime object from the $data["date"] string.

$diff in a dateinterval object. to get the number of days, you would need to use the dateinterval ->format() method with the '%a' format specifier to produce the whole number of days.

  • Like 1

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.