Forum

Thread tagged as: Question

Countdown based on date and time fieldtype?

I'm trying to 'jazz up' a list of tenders by showing how many days left there is to submit a bid. Is there a format function that already exists in Perch that will allow me to easily specify a countdown to a date and time defined by the user using perch:content type="date" time="true"?

Essentially, this sort of function:

<?php 
    $date = strtotime("March 7, 2016 2:00 PM");
    $remaining = $date - time();
    $days_remaining = floor($remaining / 86400);
    $hours_remaining = floor(($remaining % 86400) / 3600);
    echo "$days_remaining days $hours_remaining hours left";
?>
Philip Gwynne

Philip Gwynne 1 points

  • 5 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

There's nothing built in, because this sort of relative time expression is really difficult to translate :)

There's nothing to stop you using what you have with the content from a date field though. Pop it in an each callback.

perch_content_custom('Region key', [
    'each' => function($item) {
        $date = strtotime($item['date']);
        $remaining = $date - time();
        $days_remaining = floor($remaining / 86400);
        $hours_remaining = floor(($remaining % 86400) / 3600);
        $item['date'] =  "$days_remaining days $hours_remaining hours left";
        return $item;
    },
]);

Thanks Drew, worked like a charm!