Search code examples
datenettelatte

Nette how to subtract timestamp from current date


how can i subtract number of days (timestamp|date'z') from current day (date('z')) in latte? I've tryes to use var but that does not like the formating (z).


Solution

  • Latte filters, unlike function calls, are not something that can be applied to any part of an expression – they are only optional feature of the variable printing macro.

    {expression_to_be_printed|filter1|filter2|filter3}
    

    date filter mostly just calls format method so you can use it directly:

    {(new DateTime())->format('z') - $timestamp->format('z')}
    

    This, however, will not work if the $timestamp lies in a different year. To fix this, you can use DateTime’s diff method. DateInterval, returned by the method, can then be formatted using format method which provides difference in the number of days through %a formatting string.

    {$timestamp->diff(new DateTime())->format('%a')}
    

    Fortunately, the date filter also allows formatting intervals.

    {$timestamp->diff(new DateTime())|date:'%a'}
    

    Admittedly, this looks kind of ugly. A better way would be to define a custom filter so you could just use {$post->timestamp|daysAgo}. See Latte docs about creating your own filters.