php strtotime()函数时间日期转换

在php中strtotime() 函数将任何英文文本的日期时间描述解析为 Unix 时间戳,这个函数也是我们经常会用到的,有需要的朋友参考一下.

语法:strtotime(time,now)

参数 描述

time 规定要解析的时间字符串.

now 用来计算返回值的时间戳,如果省略该参数,则使用当前时间.

例子,代码如下:

  1. <?php
  2. echo(strtotime("now"));
  3. echo(strtotime("3 October 2005"));
  4. echo(strtotime("+5 hours"));
  5. echo(strtotime("+1 week"));
  6. echo(strtotime("+1 week 3 days 7 hours 5 seconds"));
  7. echo(strtotime("next Monday"));
  8. echo(strtotime("last Sunday"));
  9. ?>
  10. //输出:
  11. 1138614504
  12. 1128290400
  13. 1138632504
  14. 1139219304
  15. 1139503709
  16. 1139180400
  17. 1138489200

Example #1 strtotime() 例子,代码如下:

  1. <?php
  2. echo strtotime("now"), "n";
  3. echo strtotime("10 September 2000"), "n";
  4. echo strtotime("+1 day"), "n";
  5. echo strtotime("+1 week"), "n";
  6. echo strtotime("+1 week 2 days 4 hours 2 seconds"), "n";
  7. echo strtotime("next Thursday"), "n";
  8. echo strtotime("last Monday"), "n";
  9. ?>

Example #2 失败检查,代码如下:

  1. <?php
  2. $str = 'Not Good';
  3. // previous to PHP 5.1.0 you would compare with -1, instead of false
  4. if (($timestamp = strtotime($str)) === false) {
  5. echo "The string ($str) is bogus";
  6. } else {
  7. echo "$str == " . date('l dS of F Y h:i:s A', $timestamp);
  8. }
  9. ?>
  10. I just found out PHP thinks slashes in date-formats aren't very european:
  11. (I guess this is not a bug, just the way it works. But correct me if I'm wrong.)
  12. <?php
  13. $date = "06/10/2011 14:28"; // 6 october 2011 2:28 pm
  14. $otherDate = "06-10-2011 14:28"; // 6 october 2011 2:28 pm
  15. echo $stamp = strtotime($date) . "<br />"; // outputs 1307708880
  16. echo $otherStamp = strtotime($otherDate) . "<br />"; // outputs 1317904080//开源代码phpfensi.com
  17. echo date("d-m", $stamp); // outputs 10-06
  18. echo date("d-m", $otherStamp); // outputs 06-10
  19. ?>