Search code examples
variablesdatedate-arithmetic

Calculate end date based on # of days and start date


I am working on script where users can make certain type of orders. Now when users make an order they can choose how long they wont it to last in # of days. Once the order is placed I need to approve their order and that approval date is recorded inside my database. Now what I need is to show inside their user panel how much days their package will last since the day of my approval. So for example if I approved their order September 08, 2013 and they choosed for the order to last 7 days, I wont them to see inside they panel for every next day they login how much days they have left, so 7days, 6days, 5days, etc... all the way to "0 Days" when they come to their panel on September 16, 2013.

I have following variables for those two values:

$row_ordersResults['date'] - the date I approved the order $row_ordersResults['drip_feed'] - # of days they wont for their order to last

I did tried to lots of combinations by myself but I am totally stuck with this and cant make it work.

Thanks for help!


Solution

  • The libraries at momentjs.com is pretty cool. But if you just wanted something simple to calculate the "date difference" between two time values, there is a relatively simple way to do it. I assume you wanted it done in Javascript.

    All you need to do is to clear out the hour/minute/second/millisecond fields of the two dates, calculate their differences in days. Put the script below in any web browser and you'll see how it works.

    <script>
    function foo() {
        var d1 = new Date(2013, 8, 12, 13, 40, 1, 333); // any date value, last 4 params can be anything
        var d2 = new Date(2013, 9, 3, 11, 42, 32, 533);
    
        d1.setHours(0); d1.setMinutes(0); d1.setSeconds(0); d1.setMilliseconds(0);
        d2.setHours(0); d2.setMinutes(0); d2.setSeconds(0); d2.setMilliseconds(0);
        daysLeft = (d2.getTime() - d1.getTime())/(24*60*60*1000);
    
        alert('Dear customer, there is(are) ' + daysLeft + ' day(s) left on your order!' );
    }
    </script>
    <a href="#" OnClick="foo()">Show Remaining Days on Order</a>
    

    EDIT: adding PHP version

    <?php
    
    $d1 = New DateTime('2013-08-28 06:25:00');
    $d2 = new DateTime(); // now
    $drip = 55;
    
    $interval = $d2->diff($d1); // time difference
    $days_left = $drip - $interval->format('%a'); // in days, subtract from drip
    echo "There are $days_left days left\n";
    
    ?>