【问题标题】:Keep leading 0 in date calculation [duplicate]在日期计算中保持前导 0 [重复]
【发布时间】:2019-02-12 23:31:45
【问题描述】:

我想根据这个月/年得到最后一个月/年,所以我使用 php 代码/计算:

<?php
$this_month = date("m");
$this_year = date("Y");
if($this_month == "01"){
$history_month = "12";
$history_year = $this_year - 1;
}
else{
$history_month = $this_month - 1;
$history_year = $this_year;
}
$history_var = $history_year."".$history_month;
?>

问题是,当我回显history_var 时,我看到的是20188 而不是 201808

如何在08 上保持领先的0

或者,有没有更简单的方法来计算上个月?

【问题讨论】:

  • 根据php手册“m是一个月的数字表示,前导零,如01到12”
  • @Sfili_81 是的,我知道,但计算正在删除 0,这是我不希望发生的!
  • 您从月份中减去 1,这会将字符串转换为 int 并将其放在前导 0 中。
  • 在进行整数数学运算时,您不能“保留”前导 0。您需要将结果转换回字符串并在前面加上 "0" 字符。
  • 你可以试试 sprintf("%02d", $this_month);

标签: php


【解决方案1】:

试试这个:

测试$history_month 是否小于 10 -> 加零

 <?php
    $this_month = date("m");
    $this_year = date("Y");
    if($this_month == "01"){
    $history_month = "12";
    $history_year = $this_year - 1;
    }
    else{
    $history_month = $this_month - 1;
    $history_year = $this_year;
    }

    $history_month = $history_month >= 10 ? $history_month : "0".$history_month;

    $history_var = $history_year."".$history_month;
    ?>

【讨论】:

  • 不知道为什么它确实有效。虽然,我确实将其编辑为更简单的if($history_month &lt; 10){$history_month = "0".$history_month;}
  • 它被否决了,因为有人将您的问题标记为重复。享受
  • 我的意思是你的回答被否决了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-10
  • 2015-03-04
  • 1970-01-01
  • 2011-08-18
  • 2016-08-21
  • 1970-01-01
相关资源
最近更新 更多