Format a date string in PHP

后端 未结 4 1484
渐次进展
渐次进展 2021-01-12 10:47

If I have a string which represents a date, like \"2011/07/01\" (which is 1st July 2011) , how would I output that in more readable forms, like:

1 July 201         


        
4条回答
  •  醉酒成梦
    2021-01-12 11:24

    As NullUserException mentioned, you can use strtotime to convert the date strings to timestamps. You can output 'intelligent' ranges by using a different date format for the first date, determined by comparing the years, months and days:

    $date1 = "2011/07/01";
    $date2 = "2011/07/11";
    
    $t1 = strtotime($date1);
    $t2 = strtotime($date2);
    
    // get date and time information from timestamps
    $d1 = getdate($t1);
    $d2 = getdate($t2);
    
    // three possible formats for the first date
    $long = "j F Y";
    $medium = "j F";
    $short = "j";
    
    // decide which format to use
    if ($d1["year"] != $d2["year"]) {
        $first_format = $long;
    } elseif ($d1["mon"] != $d2["mon"]) {
        $first_format = $medium;
    } else {
        $first_format = $short;
    }
    
    printf("%s - %s\n", date($first_format, $t1), date($long, $t2));
    

提交回复
热议问题