简体   繁体   中英

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( "Ymd 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM