SamC Posted October 6, 2017 Posted October 6, 2017 I'm trying to put a timestamp next to posts to show how long ago they were published. Is there something obvious I'm missing here as the only times I seem to be able to get are 'Today', 'Yesterday' and 3+ days ago, never '2 days ago'. <ul class="list-unstyled"> <?php $entries = $pages->find("template=blog-entry, sort=-postDate, limit=5"); foreach ($entries as $entry): $timeStampNow = $datetime->date($format = "ts"); // postDate is a Datetime field on the blog-entry template $timeStampPostDate = $entry->getUnformatted("postDate"); $difference = $timeStampNow - $timeStampPostDate; if ($difference < 86400) { $daysAgo = "Today"; } else if ($difference > 86400 && $difference < (86400 * 2)) { $daysAgo = "Yesterday"; } else { $daysAgo = date("j", $difference) . " days ago"; } ?> <li class="py-1"><a href="<?= $entry->url; ?>"><?= $entry->title; ?></a> - <?= $daysAgo; ?></li> <?php endforeach; ?> </ul> Maybe I'm not taking into consideration the actual time of day they were posted, maybe the code above does work, but I've never been able to output '2 days ago' thus far. Any advice would be awesome, thanks. [BASICS] [DETAILS] [INPUT] [OUTPUT]
abdus Posted October 6, 2017 Posted October 6, 2017 There's a function in the core for this: function wireRelativeTimeStr($ts, $abbreviate = false, $useTense = true) {...) 4
SamC Posted October 6, 2017 Author Posted October 6, 2017 8 minutes ago, abdus said: There's a function in the core for this: function wireRelativeTimeStr($ts, $abbreviate = false, $useTense = true) {...) Thanks @abdus Found it now: https://processwire.com/api/ref/datetime/relative-time-str/ I'll give it a shot.
SamC Posted October 6, 2017 Author Posted October 6, 2017 Ok, working now, I changed the date picker to include an actual time too and tested: // blog-index.php <ul class="list-unstyled"> <?php $entries = $pages->find("template=blog-entry, sort=-postDate, limit=5"); foreach ($entries as $entry): $daysAgo = $datetime->relativeTimeStr($entry->getUnformatted("postDate")); ?> <li class="py-1"><a href="<?= $entry->url; ?>"><?= $entry->title; ?></a> - <?= $daysAgo; ?></li> <?php endforeach; ?> </ul> ...and: Gotta start checking that API reference more often. 1
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now