Format a date string in PHP

匿名 (未验证) 提交于 2019-12-03 02:24:01

问题:

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 2011 1 Jul 2011  (month as three letters) 

And also, how could I make it intelligently show date ranges like "2011/07/01" to "2011/07/11" as

1 - 11 July 2001 

(without repeating the 'July' and '2011' in this case)

回答1:

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)); 


回答2:

You can convert your date to a timestamp using strtotime() and then use date() on that timestamp. On your example:

$date = date("j F Y", strtotime("2011/07/01")); // 1 July 2011 $date = date("j M Y", strtotime("2011/07/01")); // 1 Jul 2011 


回答3:

As for the second one:

$time1 = time(); $time2 = $time1 + 345600; // 4 days if( date("j",$time1) != date("j",$time2) && date("FY",$time1) == date("FY",$time2) ){    echo date("j",$time1)." - ".date("j F Y",$time2); } 

Can be seen in action here

Just make up more conditions



回答4:

I would use strtotime AND strftime. Is a much simpler way of doing it.

By example, if a have a date string like "Oct 20 18:29:50 2001 GMT" and I want to get it in format day/month/year I could do:

$mystring = "Oct 20 18:29:50 2001 GMT"; printf("Original string: %s\n", $mystring); $newstring = strftime("%d/%m/%Y", strtotime($mystring)); printf("Data in format day/month/year is: %s\n", $newstring); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!