繁体   English   中英

如何以两位数显示数字

[英]how to display number in two digits

我想选择在本月和两个月前到期的名称。

  $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。 我该如何解决

您可以简单地使用sprintf()格式化数字。 例如:

$t=date('Y');
$q = date('m');

for($e=$q;$e<=($q+2);$e++){
  $ren = $t.'-'. sprintf("%'.02d", $e);
  var_dump($ren);
}

可以在docs中找到有关sprintf()更多信息。

但是,由于您正在使用日期,为什么不使用\\ 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

这是一个比较这两种方法的工作示例

使用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%' 

暂无
暂无

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

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