PHP中的DatedIF等价物

时间:2015-05-11 17:36:10

标签: php codeigniter

需要帮助才能在PHP中找到一个能够返回两个给定日期之间的年,月和日期的函数

例如:DATEDIF(" 20-05-2015"," 20-05-2015"," m")将在Excel中返回1个月但使用date_diff我只需要31天。

1 个答案:

答案 0 :(得分:0)

在PHP> = 5.2.0中使用日期的正确方法是使用DateTime,即:

$startRaw = '2013-05-10 12:04:58';
$start = DateTime::createFromFormat('Y-m-d H:i:s', $startRaw );

$endRaw = date("2015-05-10 12:04:58");
$end = DateTime::createFromFormat('Y-m-d H:i:s', $endRaw );

$diff = $start->diff($end);
echo 'Difference: ' . $diff->format('%y years') . "\n";

输出:

Difference: 2 years

演示:

http://ideone.com/3GzQsU

format
  

format参数中识别以下字符   串。每个格式字符必须以百分号(%)为前缀。

% Literal % % 
Y Years, numeric, at least 2 digits with leading 0 01, 03 
y Years, numeric 1, 3 
M Months, numeric, at least 2 digits with leading 0 01, 03, 12 
m Months, numeric 1, 3, 12 
D Days, numeric, at least 2 digits with leading 0 01, 03, 31 
d Days, numeric 1, 3, 31 
a Total amount of days 4, 18, 8123 
H Hours, numeric, at least 2 digits with leading 0 01, 03, 23 
h Hours, numeric 1, 3, 23 
I Minutes, numeric, at least 2 digits with leading 0 01, 03, 59 
i Minutes, numeric 1, 3, 59 
S Seconds, numeric, at least 2 digits with leading 0 01, 03, 57 
s Seconds, numeric 1, 3, 57 
R Sign "-" when negative, "+" when positive -, + 
r Sign "-" when negative, empty when positive -,  

详细了解DateTime class