strtotime函数常见用法与关键字解析
在之前关于如何计算上个月今天的文章中,我们曾指出在使用 strtotime("-1 month") 获取上月同日时会遇到特定问题,
这也促使了本文的撰写,文章将涵盖以下核心内容:
•strtotime函数的一些用法
•strtotime函数的实现基本原理
•strtotime(”-1 month”)求值失败的原因
strtotime函数的具体应用场景
1、 strtotime("JAN")与 strtotime("January")
这两种写法效果一致,均返回指定月份的对应日期;若该月不存在此日期(如3月31日对应2月),则自动顺延至下个月。例如在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"))), "
";
在PHP源码中,first 与星期和天的组合处理是分离的。即 first day 对应一种特定操作,在最终的C语言实现中,会将天的值强制设为1,即 time 结构体中的 d 字段被指定为1,相关代码如下:
switch (time->relative.first_last_day_of) {
case 1: /* first */
time->d = 1;
break;
case 2: /* last */
time->d = 0;
time->m++;
break;
}
3、previous和next关键字
与 first 类似,previous 关键字也可与星期或天组合,表示指定时间的前一个星期几或前一天。代码如下:
echo date("Y-m-d H:i:s", strtotime("previous sunday", strtotime("2011-02-01"))), "
";
程序输出: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"))), "
";
程序输出: 2011-01-30 00:00:00
当 last 表示“最后”时,其场景是指定日期所在月的最后一天,效果等同于 date("t")。例如求2000年2月的最后一天:
echo date("Y-m-d H:i:s", strtotime("last day", strtotime("2000-02-01"))), "
";
first、previous、last 和 this 关键字在 re 文件中属于同一组处理逻辑。
5、 back和front关键字
这两个关键字用于对一天中的小时进行向前和向后偏移操作,调用格式如下:
echo date("Y-m-d H:i:s", strtotime("back of 24", strtotime("2011-02-01"))), "
";
echo date("Y-m-d H:i:s", strtotime("front of 24", strtotime("2011-02-01"))), "
";
• 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 目录下。作为标准内置函数,其定义格式规范,如下所示:
PHP_FUNCTION(strtotime)
// 处理输入,判断是否存在第二个参数
// 调用相关函数,完成字符串解析和结果计算
// 返回最终结果
}
在输入处理阶段,先识别并处理两个参数都存在的情况;若非此种状态,则处理第二个参数缺失的情况;若两者皆无,则报错并返回 FALSE。
strtotime 的第一个参数为字符串,鉴于其复杂性,PHP 使用了词法解析工具 re2c。在 /ext/date/lib 目录下,parse_date.re 文件展示了原始的 re 规则。当用户传入字符串时,该程序负责处理,并根据字符串内容匹配不同的处理函数。例如 strtotime("yesterday") 调用时,分析字符串会匹配 yesterday,对应函数如下:
'yesterday'
{
DEBUG_OUTPUT("yesterday");
TIMELIB_INIT;
TIMELIB_HAVE_RELATIVE();
TIMELIB_UNHAVE_TIME();
s->time->relative.d = -1;
TIMELIB_DEINIT;
return TIMELIB_RELATIVE;
}
此处涉及几个关键的结构体定义:
typedef struct Scanner {
int fd;
uchar *lim, *str, *ptr, *cur, *tok, *pos;
unsigned int line, len;
struct timelib_error_container *errors;
struct timelib_time *time;
const timelib_tzdb *tzdb;
} Scanner;
typedef struct timelib_time {
timelib_sll y, m, d; /* Year, Month, Day */
timelib_sll h, i, s; /* Hour, mInute, Second */
double f; /* Fraction */
int z; /* GMT offset in minutes */
char *tz_abbr; /* Timezone abbreviation (display only) */
timelib_tzinfo *tz_info; /* Timezone structure */
signed int dst; /* Flag if we were parsing a DST zone */
timelib_rel_time relative;
timelib_sll sse; /* Seconds since epoch */
unsigned int have_time, have_date, have_zone, have_relative, have_weeknr_day;
unsigned int sse_uptodate; /* !0 if the sse member is up to date with the date/time members */
unsigned int tim_uptodate; /* !0 if the date/time members are up to date with the sse member */
unsigned int is_localtime; /* 1 if the current struct represents localtime, 0 if it is in GMT */
unsigned int zone_type; /* 1 time offset,
* 3 TimeZone identifier,
* 2 TimeZone abbreviation */
} timelib_time;
typedef struct timelib_rel_time {
timelib_sll y, m, d; /* Years, Months and Days */
timelib_sll h, i, s; /* Hours, mInutes and Seconds */
int weekday; /* Stores the day in 'next monday' */
int weekday_behavior; /* 0: the current day should *not* be counted when advancing forwards; 1: the current day *should* be counted */
int first_last_day_of;
int invert; /* Whether the difference should be inverted */
timelib_sll days; /* Contains the number of *days*, instead of Y-M-D differences */
timelib_special special;
unsigned int have_weekday_relative, have_special_relative;
} timelib_rel_time;
strtotime("-1 month")求值失败的原因
虽然 strtotime("-1 month") 在后一个月天数少于前一个月时会出现求值异常,但从本质上看,这并非错误。PHP 的这种实现方式有其合理性,只是由于用户需求不同,导致该方法在某些场景下被视为求值失败。
观察其实现过程,若无第二个参数,程序默认使用当前时间。第一个参数传入 "-1 month" 字符串,其在 re 文件中对应的正则表达式为:
reltextunit = (('sec'|'second'|'min'|'minute'|'hour'|'day'|'fortnight'|'forthnight'|'month'|'year') 's'?) | 'weeks' | daytext;
relnumber = ([+-]*[ /t]*[0-9]+);
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日,程序会自动将日期调整到下一个月。