我想知道上周第一天的日期:
$date = new DateTime(NULL, new DateTimeZone('Pacific/Wake'));
$date = $date->modify('previous week');
$date = $date->format('Y-m-d');
和
$date = new DateTime(NULL, new DateTimeZone('Pacific/Wake'));
$date = $date->modify('last week');
$date = $date->format('Y-m-d');
两者都有效。 但是有什么不同吗?
答案 0 :(得分:5)
它们是相同的,如果你愿意,可以自己确认一下,PHP源代码可以在github上找到。
https://github.com/php/php-src/blob/master/ext/date/php_date.c#L1443
PHP_FUNCTION(strtotime)
{
...
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 */
所以它调用timelib_strtotime
,哪里可以找到它?幸运的是,这也是在线
https://github.com/php/php-src/blob/master/ext/date/lib/parse_date.c#L24743
timelib_time* timelib_strtotime(char *s, int len, struct timelib_error_container **errors, const timelib_tzdb *tzdb, timelib_tz_get_wrapper tz_get_wrapper)
{
...
do {
t = scan(&in, tz_get_wrapper);
#ifdef DEBUG_PARSER
printf("%d\n", t);
#endif
} while(t != EOI);
...
依赖于scan
:
https://github.com/php/php-src/blob/master/ext/date/lib/parse_date.c#L835
static int scan(Scanner *s, timelib_tz_get_wrapper tz_get_wrapper)
{
...
while(*ptr) {
i = timelib_get_relative_text((char **) &ptr, &behavior);
调用timelib_get_relative_text
https://github.com/php/php-src/blob/master/ext/date/lib/parse_date.c#L561
static timelib_sll timelib_get_relative_text(char **ptr, int *behavior)
{
while (**ptr == ' ' || **ptr == '\t' || **ptr == '-' || **ptr == '/') {
++*ptr;
}
return timelib_lookup_relative_text(ptr, behavior);
}
调用timelib_lookup_relative_text
:
https://github.com/php/php-src/blob/master/ext/date/lib/parse_date.c#L536
static timelib_sll timelib_lookup_relative_text(char **ptr, int *behavior)
{
...
for (tp = timelib_reltext_lookup; tp->name; tp++) {
if (strcasecmp(word, tp->name) == 0) {
value = tp->value;
*behavior = tp->type;
}
}
...
}
反过来又使用在文件顶部定义的名为timelib_reltext_lookup
的结构集:
https://github.com/php/php-src/blob/master/ext/date/lib/parse_date.c#L248
static timelib_lookup_table const timelib_reltext_lookup[] = {
{ "first", 0, 1 },
{ "next", 0, 1 },
{ "second", 0, 2 },
{ "third", 0, 3 },
{ "fourth", 0, 4 },
{ "fifth", 0, 5 },
{ "sixth", 0, 6 },
{ "seventh", 0, 7 },
{ "eight", 0, 8 },
{ "eighth", 0, 8 },
{ "ninth", 0, 9 },
{ "tenth", 0, 10 },
{ "eleventh", 0, 11 },
{ "twelfth", 0, 12 },
{ "last", 0, -1 },
{ "previous", 0, -1 },
{ "this", 1, 0 },
{ NULL, 1, 0 }
};
希望这足以证明它们在各方面都是相同的。
答案 1 :(得分:1)
单词" previous"从PHP5开始支持," last"从PHP4开始。两者的结果是相同的,两者仍然有效。