简体   繁体   English

1个月在PHP中代表多少天?

[英]How many days does 1 month represent in PHP?

I see there is strange problem in php with month addition and subtraction. 我看到php有月加法和减法有奇怪的问题。

My questions are: 我的问题是:

  • does 1 month have an equivalent in days ? 1个月有相当于几天?
  • if yes, is this a common standard in all programing languages ? 如果是,这是所有编程语言的通用标准吗?

    A few examples: 几个例子:

     echo date('Ym-d',strtotime('2011-03-31 -1 months')); //2011-03-03 echo date('Ym-d',strtotime('2011-03-30 -1 months')); //2011-03-02 echo date('Ym-d',strtotime('2011-03-29 -1 months')); //2011-03-01 echo date('Ym-d',strtotime('2011-03-28 -1 months')); //2011-02-28 
  • From your examples, it looks like it's subtracting 1 from the month part, and then correcting for illegal dates. 从您的示例中,它看起来是从月份部分中减去1,然后更正非法日期。 Your second example: 你的第二个例子:

    2011-03-30 - 1 month = 2011-02-30 . 2011-03-30 - 1 month = 2011-02-30 This date does not exist, as February 2011 had only 28 days. 这个日期不存在,因为2011年2月只有28天。 30 - 28 = 2 , so it puts it as the 2nd day of the following month. 30 - 28 = 2 ,因此它将其作为下个月的第2天。

    However, I have not found documentation about this. 但是,我还没有找到关于此的文档。

    Either way, assuming I'm right, the answer to your question is no , "1 month" does not have a (constant) equivalent in days, it depends on the input. 无论哪种方式,假设我是对的,你的问题的答案是否定的 ,“1个月”没有(天数)等于天数,这取决于输入。

    The way strtotime parses date information is going to be very valuable here. strtotime解析日期信息的方式在这里非常有价值。

    What you seem to want is the first day of the previous month, right? 似乎想要的是上个月的第一天,对吗?

    Well, you can chain together many of these relative commands. 好吧,你可以许多这些相关命令链接在一起 For example, from the PHP interactive shell: 例如,从PHP交互式shell:

    php > $d = date_create('2011-03-28 first day -1 month'); if($d) echo $d->format('Y-m-d H:i:s'); else echo "Failed.";
    2011-02-01 00:00:00
    php > $d = date_create('2011-03-29 first day -1 month'); if($d) echo $d->format('Y-m-d H:i:s'); else echo "Failed.";
    2011-02-01 00:00:00
    php > $d = date_create('2011-03-30 first day -1 month'); if($d) echo $d->format('Y-m-d H:i:s'); else echo "Failed.";
    2011-02-01 00:00:00
    php > $d = date_create('2011-03-31 first day -1 month'); if($d) echo $d->format('Y-m-d H:i:s'); else echo "Failed.";
    2011-02-01 00:00:00
    php > $d = date_create('2011-04-01 first day -1 month'); if($d) echo $d->format('Y-m-d H:i:s'); else echo "Failed.";
    2011-03-01 00:00:00
    

    first day asks for the first day of the current month. first day要求当月的第一天。 Asking for -1 month goes to the previous month, on the same day. 要求-1 month到同一天的上个月。 Because we've already rewound to the first day of the month, this will always work as expected. 因为我们已经回到了本月的第一天,所以这将始终按预期工作。

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

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