2016-03-08 73 views
1

在php中,我需要找到去年四月份的年份。这样我就可以从该日期开始执行一个mysqli查询。我想要的日期是去年四月的第一天。问题是你可能在下个月或明年。例如,去年四月可能在2015年,而你在2016年1月。好的,这是我尝试过的代码,但显然它并没有工作。我如何找出去年四月,特别是去年四月的第一个月在php

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

我已经尝试了很多这种变化,似乎没有任何工作。我也搜索了一个在stackoverflow上的答案,没有太大的成功。

回答

2

这将工作,但它需要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; 

请注意,上面的代码将考虑“去年四月”到今年,如果我们目前在四月。