Search code examples
phpdatetimedrupaldrupal-7

Get only days ago the node was posted - Drupal 7


How can I get only days ago the node was posted?

E.g. If node post date is yesterday only print "1" or node post date is 1 month and 1 week ago only print "37"

I am trying to solve this by using following snippet but failed

<?php echo 'Posted: ',format_interval(time()-$node->created); ?>

Solution

  • format_interval() function formats a time interval with the requested granularity.

    For example if current Unix time is 1427868018 and node created time is 1366045256:

    • format_interval((time() - $node->created) , 1)) returns "1 year",
    • format_interval((time() - $node->created) , 2)) returns "1 year 11 months",
    • format_interval((time() - $node->created) , 3)) returns "1 year 11 months 2 weeks",
    • format_interval((time() - $node->created) , 4)) returns "1 year 11 months 2 weeks 6 days".

    If you want to display only days, you can use following code:

    $intervalSeconds = time() - $node->created;
    $intervalDays = floor($intervalSeconds / 86400);
    
    print $intervalDays;
    
    if ($intervalDays == 1) {
        print ' day';
    } else {
        print ' days';
    }
    

    It will return "715 days".