phpdateformat

PHP Human date range/duration 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 :)


Solution

  • 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.