我想选择在这个月和两个月后到期的名字。
$t=date('Y');
$q = date('m');
for($e=$q;$e<=($q+2);$e++){
$ren = $t.'-'.$e;
$sql = "select name,renewal_date from hosting_details where renewal_date LIKE '$ren%' ";
}在第一个月中,显示正确,但随后不会给出任何结果。当我回显$ren时,第一个月的结果是2016-01,第二个月的结果是2016-2。我如何解决这个问题?
发布于 2016-01-11 18:15:10
您可以简单地使用sprintf()来格式化数字。例如:
$t=date('Y');
$q = date('m');
for($e=$q;$e<=($q+2);$e++){
$ren = $t.'-'. sprintf("%'.02d", $e);
var_dump($ren);
}有关sprintf()的更多信息,请访问in the docs。
但是,既然您正在处理日期,为什么不使用\DateTime对象并让它为您完成这项工作呢?这意味着你不必做任何数据溢出逻辑等- PHP为你做了所有复杂的工作!
$begin = new DateTime( '2016-01-11' );
$numMonths = 2;
for($i=0; $i<$numMonths; $i++)
{
// e.g. increment the month and format the date.
var_dump($begin->modify( '+1 month' )->format("Y-m-d"));
// of course modify the format to "Y-m" for your code:
// $ren = $begin->modify( '+1 month')->format("Y-m");
}要获得更多信息,可以查看PHP文档中的\DateTime和\DatePeriod。
下面是比较这两种方法的working example。
发布于 2016-01-11 18:15:00
使用sprintf()可以解决您的问题:
$t=date('Y');
$q = date('m');
for($e=$q;$e<=($q+2);$e++){
$ren = sprintf('%d-%02d', $t,$e);
$sql = "select name,renewal_date from hosting_details where renewal_date LIKE '$ren%' ";
echo $sql . "\n";
}输出:
select name,renewal_date from hosting_details where renewal_date LIKE '2016-01%'
select name,renewal_date from hosting_details where renewal_date LIKE '2016-02%'
select name,renewal_date from hosting_details where renewal_date LIKE '2016-03%' https://stackoverflow.com/questions/34718643
复制相似问题