ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Calculate days since event and other calculations

June 11, 2012 10:18am

Subscribe [1]
  • #1 / Jun 11, 2012 10:18am

    Iceberg Creative

    21 posts

    Hello

    I have a case study section within a website that I am building for some energy-saving projects. One of the EE fields is a date field. I enter this date as the day the project installation was complete.

    This is what I want to do with the calculation.

    1) Get the current date
    2) Get the date of installation
    3) calculate the number of days that have passed
    4) Get the Annual Savings (also an EE field)
    5) Divide the Annual Savings by 365
    6) Multiply the result of 5) by the result of 3)
    7) Show the final result of 6) and round down to get rid of any decimal places

    The reason for doing this is to show the amount of savings to-date.

    How would I go about doing this in EE? I’m guessing that some PHP will be involved, but I’m a quick learner. Any help would be much appreciated.

    Cheers :0)

  • #2 / Jun 12, 2012 4:04am

    Iceberg Creative

    21 posts

    I have created the following PHP code, so far, to do the calculations for me.

    <?php
    
    /* Notes:  
    
    In PHP dates are stored as numbers.  The number indicates the number of seconds that have passed since January 1 1970 00:00:00 GMT
    
    */
    
    // 1) Get the current date
    $currentDate = time(); // simple method that gets todays date and time
    
    // 2) Get the date of installation
    $installationDate = gmmktime(1, 1, 1, 4, 1, 2012); // In this example it is 01:01:01 on 1/4/2012 but I am just working-out how to get this from the date field in EE
    
    // 3) calculate the number of days that have passed
    // gets the difference in seconds
    $secs = $currentDate - $installationDate;
    
    // get days by dividing
    $days = ($secs / (60 * 60 * 24) ); // 60 secs, 60 mins, 24 hours per day
    
    // this will be a decimal, e.g. 10.56 days, so lets round down
    $days = floor($days);
    
    // 4) Get the annual savings
    // Below is kWh savings
    $savings = {embed:annual_kwh_savings};
    
    // 5) Divide the annual savings by 365
    $dailySavings = $savings / 365;
    
    // 6) Multiply the result of 5) by the result of 3)
    $toDateSavings = $dailySavings * $days;
    
    // get rid of any decimal places
    $niceFormat = number_format($toDateSavings, 0); // decimal point and thousands seperator are standard with this method
    
    // 7) Show the final result of 6) 
    print $niceFormat . " kWh";
    
    ?>
.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases