简体   繁体   English

strtotime 2月错误

[英]strtotime february bug

Okay, so I do understand that if I am running the strtotime function on a day that is the 29th or higher I will incur the February bug and get a result for March instead. 好的,所以我的理解是,如果我在29日或之后的一天运行strtotime函数,我将产生2月的错误并获得3月的结果。

Also I get that if I set the date to Feb 1st, I can avoid the issue. 另外,如果将日期设置为2月1日,则可以避免此问题。

But here is the problem. 但这是问题所在。 I am rolling through the last 12 months of records to generate sales/billing numbers for tracking. 我正在浏览记录的最后12个月,以生成用于跟踪的销售/账单编号。 How do I ask for all records in February when my loop looks like this? 当我的循环看起来像这样时,如何查询二月份的所有记录?

setlocale( LC_MONETARY, 'en_US' );

$i = 0;
while( $i <= 11 ) {                 
  $select = "SELECT * FROM `my_table` " . 
            "WHERE YEAR( billing_date )  = '" . date( 'Y', strtotime( -$i . ' month' )) . "' " . 
            "  AND MONTH( billing_date ) = '" . date( 'm', strtotime( -$i . ' month' )) . "'";

  $result   = mysql_query( $select );
  $num_rows = mysql_num_rows( $result );

  $sales    = 16 * $num_rows;

  echo "<p align='center'>";
  echo   "Sales for " . date( 'M, Y', strtotime( '-' . $i . ' month' ) ) .
         "&nbsp" . money_format( '%i', $sales );
  echo "</p>";

  $i++;
}

How do I avoid the February bug? 如何避免2月的错误? Would it be an if statement? ifif语句? What would that look like? 那会是什么样?

Here is a pure SQL solution (if I correctly understand the scenario): 这是一个纯SQL解决方案(如果我正确理解了这种情况):

SELECT 
    YEAR(billing_date) AS billing_year,  
    MONTH(billing_date) AS billing_month,
    16 * COUNT(*) AS sales /* Why x16?!!! */
FROM my_table
GROUP BY YEAR(billing_date), MONTH(billing_date)

This will calculate the sales directly in SQL, so in PHP you just need a display loop. 这将直接在SQL中计算销售额,因此在PHP中,您只需要一个显示循环。

How do I ask for all records in February... 我如何索取2月的所有记录...

SELECT * FROM table WHERE MONTH(billing_date) = 2 SELECT * FROM table WHERE MONTH(billing_date)= 2

February bug? 2月错误? It's not a bug. 这不是错误。 Normalizing dates is a (useful) feature! 标准化日期是一项(有用的)功能! :-) :-)

If you want the last day in February, ask for the 0th of March. 如果要在2月的最后一天,请要求3月0日。

I don't know the "february bug", but you could try to use MySQL to subtract 1 month. 我不知道“ 2月的错误”,但是您可以尝试使用MySQL减去1个月。 Check 校验

SELECT DATE_SUB(billing_date, INTERVAL 1 MONTH) FROM my_table

=> Manual => 手动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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