jb510
jb510

Reputation: 368

How in PHP to take two unix time stamps and display a date range across months where the 2nd date is simplified

Using PHP I'd like to take two unix time stamps and display the date as such if they span different months:

December 6th 2013 - January 8th, 2014

but to show date ranges like this:

December 6th - 8th, 2013

when they don't span across a month or year.

My current code is below (obviously this doesn't do what I'm looking for). Hoping someone else has worked this out or it's hidden somewhere in date() and I just don't know about it.

<?php
// Date
$startDate = get_post_meta( get_the_ID(), 'wvc_session_start_timestamp', true );
$startDatePretty = date( 'F jS Y', $startDate);
$endDate = get_post_meta( get_the_ID(), 'wvc_session_end_timestamp', true );
$endDatePretty = date( 'F jS Y', $endDate);

$html .= '<div class="event-date">';
    // check if the custom field has a value

if( ! empty( $startDate ) ) {
    $html .= $startDatePretty;
} 

// check if the custom field has a value
if( ! empty( $endDate ) ) {
    if( $endDatePretty != $startDatePretty ) {
        $html .= ' - ' . $endDatePretty;
    }
 }

Upvotes: 0

Views: 82

Answers (2)

Glavić
Glavić

Reputation: 43582

Just check if dates are in the same month or not:

if (date('Ym', $startDate) == date('Ym', $endDate)) {
    echo date('F jS - ', $startDate), date('jS, Y', $endDate), "\n";
} else if (date('Y', $startDate) == date('Y', $endDate)) {
    echo date('F jS - ', $startDate), date('F jS, Y', $endDate), "\n";
} else {
    echo date('F jS Y - ', $startDate), date('F jS Y', $endDate), "\n";
}

demo

Upvotes: 0

jb510
jb510

Reputation: 368

Think I've got the logic worked out myself. Might be a cleaner/simpler way, but this gets me what I want for now until I optimize it.

// Date
$startDate = get_post_meta( get_the_ID(), 'wvc_session_start_timestamp', true );
$endDate = get_post_meta( get_the_ID(), 'wvc_session_end_timestamp', true );

if (empty($startDate) || empty($startDate)) {
    $startDatePretty = date( 'F jS, Y', $startDate);
    $endDatePretty = date( 'F jS, Y', $endDate);
} else {
    $startDatePretty = date( 'F jS', $startDate);
    $endDatePretty = date( 'jS, Y', $endDate);
    // Different year
    if (date('Y',$startDate) != date('Y',$endDate)) 
        $startDatePretty .= date( ', Y', $startDate );

    // Different month
    if (date('F',$startDate) != date('F',$endDate))
        $endDatePretty = date( 'F', $endDate) . $endDatePretty;
}

Upvotes: 1

Related Questions