Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Human date range/duration format

Tags:

date

php

format

PHP is so well made that I am wondering if there is a function for what I need.

For events that last more than one day, the human way to format it is complex.

Exemples...

Event one: from 2015-04-20 to 2015-04-22 could be formatted for humans like this: April 20-22 2015

Event two: from 2015-04-01 to 2015-05-31 Humans -> April-May 2015

Event three: from 2015-04-30 to 2015-05-02 Humans -> April 30 to May 2 2015

In short, never repeat what doesn't needs to be repeated. Link with "-" as much as possible.

It will have to be localized and the format could change depending of the local. For exemple, US folks like MonthName DayNumber Year but French like DayNumber MonthName Year.

I was planning on programming such formatting, but I was wondering if it already existed :)

like image 796
Guillaume Bois Avatar asked Sep 17 '25 20:09

Guillaume Bois


2 Answers

This works...

function humanDateRanges($start, $end){
    $startTime=strtotime($start);
    $endTime=strtotime($end);

    if(date('Y',$startTime)!=date('Y',$endTime)){
        echo date('F j, Y',$startTime) . " to " . date('F j, Y',$endTime);
    }else{
        if((date('j',$startTime)==1)&&(date('j',$endTime)==date('t',$endTime))){
            echo date('F',$startTime) . " to " . date('F, Y',$endTime);
        }else{
            if(date('m',$startTime)!=date('m',$endTime)){
                echo date('F j',$startTime) . " to " . date('F j, Y',$endTime);
            }else{
                echo date('F j',$startTime) . " to " . date('j, Y',$endTime);
            }
        }
    }
}

humanDateRanges("2015-04-20", "2015-04-22");
//April 20 to 22, 2015
humanDateRanges("2015-04-01", "2015-05-31");
//April to May, 2015
humanDateRanges("2015-04-30", "2015-05-02");
//April 30 to May 2, 2015
humanDateRanges("2014-05-02", "2015-05-02");
//May 2, 2014 to May 2, 2015

But I do think in some situations, even human beings need to be told that April-May will begin the 1st and end the 31st.

like image 73
RightClick Avatar answered Sep 19 '25 11:09

RightClick


Just in case someone else stumbles upon this: I've written a small library that tries to solve this problem in a way that also works with internationalization:

https://github.com/flack/ranger

It should provide a reasonable default for ltr languages (and rtl support shouldn't be too hard to add)

like image 41
user2792352 Avatar answered Sep 19 '25 10:09

user2792352