PHP日期差异

时间:2011-04-30 05:45:31

标签: php

我有两个字符串格式的日期我想从两个日期字符串中计算这些东西。 1)年份差异 例如

$date1 = "20/04/2002";
$date2= "20/04/2010";
$five_yers_back = <Five years back that is 2005>

类似地

$date2= "20/05/2010";
$a_week = "< seven days back from date2 >";

Plz帮助

2 个答案:

答案 0 :(得分:0)

使用strtotime + date

http://pl2.php.net/manual/en/function.strtotime.php
http://pl2.php.net/manual/en/function.date.php

答案 1 :(得分:0)

我确信有适合你的课程。但作为一名C程序员,我更喜欢tm结构的基础知识。 PHP等效示例

<?php

$d1 = "20/04/2002";
$d1rec = strptime( $d1, "%d/%m/%Y" );
$sec = 0;
$min = 0;
$hour = 0;
$day = $d1rec["tm_mday"];
$mon = $d1rec["tm_mon"] + 1;  # Because tm_mon is 0-11
$year = $d1rec["tm_year"];
print( "DATE: " . strftime( "%d/%m/%Y\n"
              , mktime($hour,$min,$sec,$mon,$day,$year) ) );
print( "+1WK: " . strftime( "%d/%m/%Y\n"
              , mktime($hour,$min,$sec,$mon,$day+7,$year) ) );
print( "+2WK: " . strftime( "%d/%m/%Y\n"
              , mktime($hour,$min,$sec,$mon,$day+14,$year) ) );
print( "+1YR: " . strftime( "%d/%m/%Y\n"
              , mktime($hour,$min,$sec,$mon,$day,$year+1) ) );
print( "-6MO: " . strftime( "%d/%m/%Y\n"
              , mktime($hour,$min,$sec,$mon-6,$day,$year) ) );

?>

所以基本上

  • 使用strptime将字符串解析为结构数组
  • 将数组分解为变量
  • 使用mktime将(修改的)变量重新组合成time_t整数(并处理月/年包装)
  • 使用strftime返回字符串