如果我将年份和月份作为输入(PHP),有没有办法获得前三个月。假设我给出了值,
$month = "2";
$year = 2016;
它应该像下面的数组一样返回,
Array ( [0] => '11 2015' [1] => '12 2015' [2] => '01 2016')
答案 0 :(得分:3)
你的意思是这样的吗?
function getLastMonths($year, $month, $format = 'm Y', $amount = 3) {
$months = [];
$time = strtotime($year . '-' . $month . '-01 00:00:00');
for ($i = 1; $i <= $amount; $i++) {
$months[] = date($format, strtotime('-' . $i . ' month', $time));
}
return $months;
}
所以你可以像那样使用它
$month_array = getLastMonths('2017', '06');
var_dump($month_array);
答案 1 :(得分:1)
使用
// Login Success Authenticate [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: { // check this section var isGmail = Regex.IsMatch(model.Email, @"^*@g(oogle)?mail\.com$"); if (isGmail) { return View("GmailViewCshtml", model); } else { return RedirectToLocal(returnUrl); }** } case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); } }
mktime
输出
$month = "2";
$year = 2016;
for($i=3;$i>0;$i--){
$arr[]=date("m-Y", mktime(0, 0, 0, $month-$i, 01, $year));
}
print_r($arr);
对您的评论进行编辑,将Array ( [0] => 11-2015 [1] => 12-2015 [2] => 01-2016 )
替换为m
n
答案 2 :(得分:0)
$month = "2";
$year = 2016;
$result = [];
$dateTime = DateTime::createFromFormat('Y n', "$year $month");
for($i = 0; $i < 3; $i++) {
$dateTime->sub(new DateInterval('P1M'));
$result[] = $dateTime->format('m Y');
}
var_dump(array_reverse($result));
输出
array(3) {
[0]=>
string(7) "11 2015"
[1]=>
string(7) "12 2015"
[2]=>
string(7) "01 2016"
}
答案 3 :(得分:0)
试试这段代码:
$array = array();
$month = "2";
$year = 2016;
$number_of_months = 3;
for($i = 0; $i < $number_of_months; $i++):
$sub_date = date("m Y", strtotime($year."-".$month." -1 months"));
$array[] = $sub_date;
$month = explode(" ", $sub_date)[0];
$year = explode(" ", $sub_date)[1];
endfor;
print_r($array);