Get the year of a specified month in previous 12 months?

China☆狼群 提交于 2020-01-06 18:04:07

问题


I'm trying:

$m = 'December';
$from = date('jS M Y', strtotime("first day of previous $m"));

But it's not returning a date. In use, the month will be selected by a user from a dropdown box. However, I have tried typing 'December' in place of the variable directly and it still doesn't work.

I'm expecting it to return "1st Dec 2012".


回答1:


Given your code that $m is the current month in text format, you can use something like:

$m = 'June';
$m = date('m', strtotime($m));
$c = (mktime(0,0,0,$m, 1) < time()) ? mktime(0,0,0,$m,1) : mktime(0,0,0,$m,1, date("Y") -1);
$from = date('jS M Y', $c);

What this does is it converts the month to a numerical value and stores in place of string value. Then it assigns $c to either the month of the current year, or the month of the previous year, depending on if the month of the current year is less than the current time stamp. So if the current timestamp is June 1st at 1am, then the current year will still be selected.

DEMO




回答2:


Try this

$m = '12'; // set here numeric form of month
echo $from = date('jS M Y', strtotime("01-".$m."-".(date("Y") -1)));

OR

$m = 'December';
echo $from = date('jS M Y', strtotime("01-".$m."-".(date("Y") -1)));

Output

1st Dec 2012 

Codepad Codepad2

EDIT

Try this, this is tested for january as well as december

$m = '01';
$new_m = date('m'); // get current month
if($m > $new_m) {
   $year = date("Y") -1;
} else {
   $year = date("Y");
}
echo $from = date('jS M Y', strtotime("01-".$m."-".$year));

Output

1st Jan 2013 

Codepad



来源:https://stackoverflow.com/questions/16381157/get-the-year-of-a-specified-month-in-previous-12-months

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!