格式化PHP中的日期字符串 [英] Format a date string in PHP

查看:104
本文介绍了格式化PHP中的日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个表示日期的字符串,例如2011/07/01(2011年7月1日),我将如何以更易读的形式输出:

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)

而且,如何让智能地将日期范围显示为2011/07/01至2011/07/11作为

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

1 - 11 July 2001

(不重复

推荐答案

由于提到的NullUserException,您可以使用 strtotime 将日期字符串转换为时间戳。您可以通过使用第一个日期的不同日期格式输出智能范围,通过比较年,月和日确定:

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

这篇关于格式化PHP中的日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆