深入分析PHP strtotime函数

strtotime函数的使用在时间日期处理上是非常的强大了,这里我们一起来看看strtotime函数内核与常用方法.

PHP strtotime函数将任何英文文本的日期时间描述解析为Unix时间戳[将系统时间转化成unix时间戳]

一,获取指定日期的unix时间戳 strtotime(”2009-1-22″) 示例如下:

echo strtotime(”2009-1-22“) 结果:1232553600

说明:返回2009年1月22日0点0分0秒时间戳

二,获取英文文本日期时间 示例如下:

便于比较,使用date将当时间戳与指定时间戳转换成系统时间

(1)打印明天此时的时间戳strtotime(”+1 day“)

当前时间:echo date(”Y-m-d H:i:s”,time()) 结果:2009-01-22 09:40:25

指定时间:echo date(”Y-m-d H:i:s”,strtotime(”+1 day”)) 结果:2009-01-23 09:40:25

(2)打印昨天此时的时间戳strtotime(”-1 day“)

当前时间:echo date(”Y-m-d H:i:s”,time()) 结果:2009-01-22 09:40:25

指定时间:echo date(”Y-m-d H:i:s”,strtotime(”-1 day”)) 结果:2009-01-21 09:40:25

(3)打印下个星期此时的时间戳strtotime(”+1 week“)

当前时间:echo date(”Y-m-d H:i:s”,time()) 结果:2009-01-22 09:40:25

指定时间:echo date(”Y-m-d H:i:s”,strtotime(”+1 week”)) 结果:2009-01-29 09:40:25

(4)打印上个星期此时的时间戳strtotime(”-1 week“)

当前时间:echo date(”Y-m-d H:i:s”,time()) 结果:2009-01-22 09:40:25

指定时间:echo date(”Y-m-d H:i:s”,strtotime(”-1 week”)) 结果:2009-01-15 09:40:25

(5)打印指定下星期几的时间戳strtotime(”next Thursday“)

当前时间:echo date(”Y-m-d H:i:s”,time()) 结果:2009-01-22 09:40:25

指定时间:echo date(”Y-m-d H:i:s”,strtotime(”next Thursday”)) 结果:2009-01-29 00:00:00

(6)打印指定上星期几的时间戳strtotime(”last Thursday“)

当前时间:echo date(”Y-m-d H:i:s”,time()) 结果:2009-01-22 09:40:25

指定时间:echo date(”Y-m-d H:i:s”,strtotime(”last Thursday”)) 结果:2009-01-15 00:00:00

以上示例可知,strtotime能将任何英文文本的日期时间描述解析为Unix时间戳,我们结合mktime()或date()格式化日期时间获取指定的时间戳,实现所需要的日期时间。

现在我们深入分析它的源码

源码位置:\ext\date\php_date.c,代码如下:

  1. /* {{{ proto int strtotime(string time [, int now ])
  2. Convert string representation of date and time to a timestamp */
  3. PHP_FUNCTION(strtotime)
  4. {
  5. char *times, *initial_ts;
  6. int time_len, error1, error2;
  7. struct timelib_error_container *error;
  8. long preset_ts = 0, ts;
  9. timelib_time *t, *now;
  10. timelib_tzinfo *tzi;
  11. tzi = get_timezone_info(TSRMLS_C);
  12. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, “sl”, &times, &time_len, &preset_ts) != FAILURE) {
  13. /* We have an initial timestamp */
  14. now = timelib_time_ctor();
  15. initial_ts = emalloc(25);
  16. snprintf(initial_ts, 24, “@%ld UTC”, preset_ts);
  17. t = timelib_strtotime(initial_ts, strlen(initial_ts), NULL, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper); /* we ignore the error here, as this should never fail */
  18. timelib_update_ts(t, tzi);
  19. now->tz_info = tzi;
  20. now->zone_type = TIMELIB_ZONETYPE_ID;
  21. timelib_unixtime2local(now, t->sse);
  22. timelib_time_dtor(t);
  23. efree(initial_ts);
  24. } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, “s|l”, &times, &time_len, &preset_ts) != FAILURE) {
  25. /* We have no initial timestamp */
  26. now = timelib_time_ctor();
  27. now->tz_info = tzi;
  28. now->zone_type = TIMELIB_ZONETYPE_ID;
  29. timelib_unixtime2local(now, (timelib_sll) time(NULL));
  30. } else {
  31. RETURN_FALSE;
  32. }
  33. if (!time_len) {
  34. timelib_time_dtor(now);
  35. RETURN_FALSE;
  36. }
  37. t = timelib_strtotime(times, time_len, &error, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper);
  38. error1 = error->error_count;
  39. timelib_error_container_dtor(error);
  40. timelib_fill_holes(t, now, TIMELIB_NO_CLONE);
  41. timelib_update_ts(t, tzi);
  42. ts = timelib_date_to_int(t, &error2);
  43. timelib_time_dtor(now);
  44. timelib_time_dtor(t);
  45. if (error1 || error2) {
  46. RETURN_FALSE;
  47. } else {
  48. RETURN_LONG(ts);
  49. }
  50. }
  51. /* }}} */

strtotime函数在使用strtotime(“-1 month”)求上一个月的今天时会出一些状况,

因此也引出写这篇文章,本文包括如下内容:

strtotime函数的一些用法

strtotime函数的实现基本原理

strtotime(“-1 month”)求值失败的原因

strtotime函数的一些用法

1、strtotime(“JAN”)和strtotime(“January”)

这两个用法的效果是一样的,都是返回指定月份的今天,如果指定月份没有今天,则顺延到下一个月。 如在2011-03-31计算二月,代码:

echo date("Y-m-d H:i:s", strtotime("feb", strtotime("2011-03-31")));

程序会输出: 2011-03-03 00:00:00。 从表象来看,这个结果也许不一定是我们想要的,但是这也算是一种解决方案,这种方案是由什么决定的呢? strtotime函数在执行月份的计算时只计算了月份,相当于直接将月份设置为指定的月份的值,而如jan,january都会有一个对应内部数值。

2、first关键字

first是一个辅助型的关键字,它可以与星期,天等可以指定确认值的关键字组合使用,如求2011年的第一个星期天:

echo date("Y-m-d H:i:s", strtotime("second sunday",strtotime("2011-01-01"))), "<br />";

在PHP的源码中,对于first与星期和天的组合使用是分开的,即first day对应一个处理操作,在最终的C实现中,天的值指定为1,即time结构中的d字段指定为1,如下代码:

  1. switch (time->relative.first_last_day_of) {
  2. case 1: /* first */
  3. time->d = 1;
  4. break;
  5. case 2: /* last */
  6. time->d = 0;
  7. time->m++;
  8. break;
  9. }

3、previous和next关键字

与first类似,previous关键字可以与星期,天组合使用,表示指定时间的前一个星期几或前一天,如下所示代码:

echo date("Y-m-d H:i:s", strtotime("previous sunday", strtotime("2011-02-01"))), "<br />";

程序会输出:2011-01-30 00:00:00

程序求2011-02-01的前一个星期天.

next关键字与previous相反,它表示下一个星期几或后一天.

4、last关键字

last关键字既可以作为上一个,也可以作为最后一个,如求上一个星期天的日期,代码如下:

echo date("Y-m-d H:i:s", strtotime("last sunday", strtotime("2011-02-05"))), "<br />";

程序会输出:2011-01-30 00:00:00

当程序作为最后时,其应用场景是指定日期所在月的最后一天,相当于date(“t”)的结果,如求2000年2月的最后一天:

echo date("Y-m-d H:i:s", strtotime("last day", strtotime("2000-02-01"))), "<br />";

first、previous、last和this关键字在re文件中属于同一组。

5、back和front关键字

这两个关键字是对一天中的小时的向前和向后操作,其调用格式如下:

  1. echo date("Y-m-d H:i:s", strtotime("back of 24", strtotime("2011-02-01"))), "<br />";
  2. echo date("Y-m-d H:i:s", strtotime("front of 24", strtotime("2011-02-01"))), "<br />";

back表示将时间设置指定小时值的后一个小时的15分的位置,如果是24点,则算到第二天的0点15分.

front表示将时间设置指定小时值的前一个小时的45分的位置,如果是0点,则算前一天的23点45分.

上面的代码输出:2011-02-02 00:15:00 2011-02-01 23:45:00,其中back of和front of后接的数组必须大于等于0并且小于等于24。

strtotime函数的实现基本原理

官方文档对于strtotime函数的说明是这样的:本函数预期接受一个包含美国英语日期格式的字符串并尝试将其解析为 Unix 时间戳(自 January 1 1970 00:00:00 GMT 起的秒数),其值相对于 now 参数给出的时间,如果没有提供此参数则用系统当前时间.

这是一个标准PHP内置函数,从PHP4起就已经存在。strtotime函数是以一个扩展的方式加载进来的,在ext/date目录下有其全部实现。 作为一个标准的内置函数,其定义格式也是标准的,如下:

  1. PHP_FUNCTION(strtotime)
  2. // 处理输入,对于是否有第二个参数有没的处理
  3. // 调用相关函数,实现字符串的解析和结果计算
  4. // 返回结果
  5. }

在输入处理中,先识别两个参数都存在的情况并进行处理,如果不是此种状态,则处理第二个参数不存在的情况,如果都没有,则报错,返回FALSE.

strtotime函数的第一个参数是一个字符串,对于这个字符串,由于其复杂性,PHP使用了其词法解析一样的工具:re2c,在/ext/date/lib目录下,从parse_date.re文件我们可以看到其原始的re文件,当用户以参数的形式传入一个字符串,此字符串将交给此程序处理,针对其字符串的不同,匹配不同的处理函数,如strtotime(“yesterday”)调用,分析字符串时,将匹配yesterday字符串,此字符串对应函数如下:

  1. 'yesterday'
  2. {
  3. DEBUG_OUTPUT("yesterday");
  4. TIMELIB_INIT;
  5. TIMELIB_HAVE_RELATIVE();
  6. TIMELIB_UNHAVE_TIME();
  7. s->time->relative.d = -1;
  8. TIMELIB_DEINIT;
  9. return TIMELIB_RELATIVE;
  10. }

这里有几个关键的结构体:

  1. typedef struct Scanner {
  2. int fd;
  3. uchar *lim, *str, *ptr, *cur, *tok, *pos;
  4. unsigned int line, len;
  5. struct timelib_error_container *errors;
  6. struct timelib_time *time;
  7. const timelib_tzdb *tzdb;
  8. } Scanner;
  9. typedef struct timelib_time {
  10. timelib_sll y, m, d; /* Year, Month, Day */
  11. timelib_sll h, i, s; /* Hour, mInute, Second */
  12. double f; /* Fraction */
  13. int z; /* GMT offset in minutes */
  14. char *tz_abbr; /* Timezone abbreviation (display only) */
  15. timelib_tzinfo *tz_info; /* Timezone structure */
  16. signed int dst; /* Flag if we were parsing a DST zone */
  17. timelib_rel_time relative;
  18. timelib_sll sse; /* Seconds since epoch */
  19. unsigned int have_time, have_date, have_zone, have_relative, have_weeknr_day;
  20. unsigned int sse_uptodate; /* !0 if the sse member is up to date with the date/time members */
  21. unsigned int tim_uptodate; /* !0 if the date/time members are up to date with the sse member */
  22. unsigned int is_localtime; /* 1 if the current struct represents localtime, 0 if it is in GMT */
  23. unsigned int zone_type; /* 1 time offset,
  24. * 3 TimeZone identifier,
  25. * 2 TimeZone abbreviation */
  26. } timelib_time; //开源软件:phpfensi.com
  27. typedef struct timelib_rel_time {
  28. timelib_sll y, m, d; /* Years, Months and Days */
  29. timelib_sll h, i, s; /* Hours, mInutes and Seconds */
  30. int weekday; /* Stores the day in 'next monday' */
  31. int weekday_behavior; /* 0: the current day should *not* be counted when advancing forwards; 1: the current day *should* be counted */
  32. int first_last_day_of;
  33. int invert; /* Whether the difference should be inverted */
  34. timelib_sll days; /* Contains the number of *days*, instead of Y-M-D differences */
  35. timelib_special special;
  36. unsigned int have_weekday_relative, have_special_relative;
  37. } timelib_rel_time;

s->time->relative.d = -1;所表示的意思是当前时间的相对天数是-1,这只是中间词法解析的中间结果,但是最后结果是通过这些中间结果计算出来的.

strtotime(“-1 month”)求值失败的原因

虽然strtotime(“-1 month”)这种方法对于后一个月比前一个月的天数的情况会求值失败,但是从其本质上来说,这并没有错。 PHP这样实现也无可厚非。只是我们的需求决定了我们不能使用这种方法,因此我们称其为求值失败。

我们来看它的实现过程,由于没有第二个参数,所以程序使用默认的当前时间,第一个参数传入的是-1 month字符串,这个字符串所对应的re文件中的正则为:

  1. reltextunit = (('sec'|'second'|'min'|'minute'|'hour'|'day'|'fortnight'|'forthnight'|'month'|'year') 's'?) | 'weeks' | daytext;
  2. relnumber = ([+-]*[ \t]*[0-9]+);
  3. relative = relnumber space? (reltextunit | 'week' );

最终relative会对应一系列操作,程序会识别出前面的-1 和后面的month字符串,month对应一种操作类型:TIMELIB_MONTH,在此之后,根据识别出来的数字和操作类型执行操作,如下代码:

case TIMELIB_MONTH: s->time->relative.m += amount * relunit->multiplier; break;

如上代码,则是直接记录月份的相对值减一,但是对于类似于3月31号这样的情况,2月没有31号,程序会自动将日期计算到下一个月.