2016-09-13 06:27
浏览 165

PHP - mktime()函数返回错误的时间

The Problematic Code

I am trying to build a time using some string values extracted from a file. This is basically the code that runs.

$hour = "18";            
$minutes = "0";
$month = "28";
$day = "4";
$year = "2016";
echo("<div>"."Current PHP version: " . phpversion()."</div>");  
echo("<div>hour :: ".(int)$hour."</div>");  
echo("<div>minutes :: ".(int)$minutes."</div>");        
echo("<div>month :: ".(int)$month."</div>");        
echo("<div>day :: ".(int)$day."</div>");        
echo("<div>year :: ".(int)$year."</div>");                  
$built_time = mktime((int)$hour,(int)$minutes,0,(int)$month,(int)$day,(int)$year);
echo("<div>  Built Time [Y-m-d H:i:s]: ".date( 'Y-m-d H:i:s',$built_time)."</div>");

The Wrong Results

The output is receive for this is:

Output for given code snippet

Several more attempts yielded the following results

Other attempts

As you can see sometimes it does provide the correct result! Why does this happen. It cannot be a timezone issue since its giving dates which are years into the future.

As per mktime() documentation the parameter sequence is also correct. Wonder why this call is failing.

图片转代码服务由CSDN问答提供 功能建议


我正在尝试使用一些字符串构建时间 从文件中提取的值。 这基本上就是运行的代码。

  $ hour =“18”;  
 $ minutes =“0”; 
 $ month =“28”; 
 $ day =“4”; 
 $ year =“2016”; 
echo(“&lt; div&gt;”。“当前的PHP版本 :“。phpversion()。”&lt; / div&gt;“);  
echo(“&lt; div&gt; hour ::”。(int)$ hour。“&lt; / div&gt;”);  
echo(“&lt; div&gt; minutes ::”。(int)$ minutes。“&lt; / div&gt;”);  
echo(“&lt; div&gt; month ::”。(int)$ month。“&lt; / div&gt;”);  
echo(“&lt; div&gt; day ::”。(int)$ day。“&lt; / div&gt;”);  
echo(“&lt; div&gt; year ::”。(int)$ year。“&lt; / div&gt;”);  
 $ built_time = mktime((int)$ hour,(int)$ minutes,0,(int)$ month,(int)$ day,(int)$ year); 
echo(“&lt; div&gt; Built time  [Ymd H:我:s]:“。日期('Ymd H:i:s',$ built_time)。”&lt; / div&gt;“); 
 <  hr> 




正如您所看到的,它确实提供了正确的结果! 为什么会这样呢? 它不是一个时区问题,因为它给出的日期是未来几年。

根据 mktime()文档参数序列也是正确的。 不知道为什么这个电话会失败。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dongwalun2507 2016-09-13 06:34

    The result is correct according to your inputs.

    mktime accetps month value to be between 1-12. In each of your attempts except last one month values are 28,28,21,21.

    So when the value of month is more then 12, it references the appropriate month in the following year(s). So in your first two case it would be 04 and and in 3rd and 4th it would be 09.

    When you pass value of month greater then 12 it calculates the N months after current month. So in first two cases it's April 2018(04) and and in 3rd and 4th it's September(09) 2017.

    So the outputs are correct according to your inputs.

    解决 无用
    打赏 举报
  • 查看更多回答(3条)