开发者

ISO-8601 numeric representation of the day of the week ("N") in PHP using the date() function always returns 3

Trying to get the ISO-8601 numeric representation of the day of the week ("N") in PHP using the date() function; however, it keeps returning "3" no matter what day I use with mktime().

<?php

$date = date( "Y-m-d H:i:s", mktime(0, 0, 0, 9, 16, 2011) );
//$date = date( "Y-m-d H:i:s", mktime(0, 0, 0,开发者_高级运维 9, 17, 2011) );

print_r(date('N', $date));

?>

Output: 3


You shouldn't feed a date string into the second argument for date(), it should be an integer containing the Unix timestamp (the value returned from mktime()). See the date() documentation.

$date = mktime(0, 0, 0, 9, 16, 2011);
var_dump(date('N', $date)); // string(1) "5"

With your original code:

$date = date( "Y-m-d H:i:s", mktime(0, 0, 0, 9, 16, 2011) );
print_r(date('N', $date));

The value of $date is "2011-09-16 00:00:00". This is not an integer, and certainly not the Unix timestamp for that date/time; because of that, date() cannot work with the value and reverts back to using the Unix epoch (0 timestamp) which is 1 Jan 1970. Also, an E_NOTICE message stating "A non well formed numeric value encountered in [file] on line [line]" is issued.


PHP is trying to interpret the string generated by date( "Y-m-d H:i:s", mktime(0, 0, 0, 9, 16, 2011) ); as a date, but PHP uses seconds since epoch as a datatime. You can just pass the result of mktime into the second data function call like this:

$dateTime = mktime(0, 0, 0, 9, 16, 2011)
$date = date("Y-m-d H:i:s",  $dateTime);
echo date('N', $dateTime);
// results in "5"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜