Skip to content

Instantly share code, notes, and snippets.

@rtpHarry
Created May 21, 2021 23:56
Embed
What would you like to do?
Convert a start and end timestamp into a nicely formatted and joined up date range
<?php
/**
* Filter for Unlimited Elements to format a date range, from two timestamps
*/
function filter_format_date_range($startTimeStamp, $endTimeStamp){
$displayDate = "";
if($startTimeStamp == $endTimeStamp) {
// same date
$displayDate = date('j M Y', $endTimeStamp);
} else {
$startDate = getDate($startTimeStamp);
$endDate = getDate($endTimeStamp);
if($startDate["year"] == $endDate["year"]) {
if($startDate["mon"] == $endDate["mon"]) {
// same year, same month
$displayDate = date('j-', $startTimeStamp) . date('j M Y', $endTimeStamp);
} else {
// same year, diff month
$displayDate = date('j M-', $startTimeStamp) . date('j M Y', $endTimeStamp);
}
} else {
// different years, return full date range
$displayDate = date('j M Y-', $startTimeStamp) . date('j M Y', $endTimeStamp);
}
}
return $displayDate;
}
add_filter( 'format_date_range', 'filter_format_date_range', 10, 2 );
<!-- Unlimited Elements Twig Template -->
{% set startDate = getPostMeta(current_post.id,"start-date") %}
{% set endDate = getPostMeta(current_post.id,"end-date") %}
{% set formattedDate = apply_filters('format_date_range', startDate, endDate) %}
<div>{{formattedDate}}</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment