简体   繁体   English

我如何找出去年四月的一年,特别是去年四月一号的PHP

[英]How do I find out the year last April, specifically the 1st of the last April in php

In php I need to find the year that last April is in. This is so I can do a mysqli query from that date. 在php中,我需要查找去年四月的年份。因此,我可以从该日期开始进行mysqli查询。 The date I want is the 1st of last April. 我想要的日期是去年四月1日。 The problem is that you might be in the next month, or next year. 问题是您可能在下个月或下一年。 For instance last April could be in 2015 and you are in January 2016. Ok this is the code I have tried, but obviously it doeesn't work. 例如,去年4月可能是2015年,而您是2016年1月。好吧,这是我尝试过的代码,但是显然它不起作用。

    $datestring='first day of last april';
$date=date_create($datestring);
echo nulldate_full($date->format('Y-m'));

I have tried a lot of variations of this and nothing seems to work. 我已经尝试了很多这种变化,但似乎没有任何效果。 I have also search for an answer on stackoverflow also, without much success. 我也在寻找关于stackoverflow的答案,但没有成功。

This will work, although it requires some lines of code : 这将起作用,尽管它需要一些代码行

// first of April this year
$april_this_year = date('Y-04-01');

// current date
$today = date('Y-m-d');

// current year
$year = date('Y');

// if April in this year is yet to come   
if ($april_this_year >= $today) {
    // then it was previous year
    --$year;
}

// show it
echo $year;

Please note that the above code will consider "last April" to be this year if we are currently in April. 请注意,如果我们当前在4月,则上述代码会将“去年4月”视为今年。

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

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