【问题标题】:PHP, MySQL date calculationsPHP、MySQL 日期计算
【发布时间】:2021-04-27 22:47:27
【问题描述】:

我正在尝试添加迄今为止的几周,两者都将从数据库中获取,我成功地获取了所需的两个,但我不知道如何进行计算。到目前为止,我尝试使用“strtotime”,但它给了我一些奇怪的结果

    <?php 

$servername = "localhost"; 
$username = "root"; 
$password = "password"; 
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
    
    $sql = "SELECT startdate  // <- DATE WE WANT TO ADD WEEKS TO
            FROM database
            ORDER BY id 
            DESC limit 1";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      $recoredDate = $row["startdate"];
    

      
    $sql2 = "SELECT ready // <- INT NUMBER REPRESENT NUMBER OF WEEKS
            FROM crop
            ORDER BY id 
            DESC limit 1";
    $result2 = $conn->query($sql2);

    if ($result2->num_rows > 0) {
    // output data of each row
    while($row = $result2->fetch_assoc()) {
      $weeks = $row["ready"];

      }
    } else {
      echo "No Result";
    }
?>

 <p>
<div align=center>

<?php echo "$recoredDate";?> - Date from DB
<p>
<?php echo "$weeks";?> Weeks to add
<p>
<?php echo "$recoredDate",strtotime ("+ $weeks week");?> Wierd result 
</div>
</p>


<?php
    }
    }
?>

我该如何以正确的方式做到这一点?期望的结果应该是打印 $recoredDate + $weeks。

【问题讨论】:

    标签: php mysql date


    【解决方案1】:

    试试

    $str = strtotime("+".$weeks." weeks", strtotime($recoredDate));
    echo date("Y-m-d", $str);
    

    如果没有第二个参数(也是时间戳),strtotime 将返回当前时间戳,在您的示例中添加 x 周。如果你想给一个日期加上星期,然后以某种格式使用日期,首先你必须给一个日期的时间戳值加上星期,然后用 date() 函数格式化。

    【讨论】:

      【解决方案2】:

      您可以先将几周变成几天。考虑到一周有 7 天,您会得到这样的结果:

      <?php
        $date = "2019-05-10";  // Your date from database
        $weeks = 3; // Your number of weeks from database
        $days = $weeks * 7; // Transform weeks to days
      
        $newDate = date('Y-m-d', strtotime($date. ' + '.$days.' days')); 
        echo $newDate;
       ?>
      

      此外,我建议您避免将 SQL 查询放在 while 循环中。这是不好的做法。

      【讨论】:

      • 谢谢你汤姆利马,很好的例子!我已经使用了上面的代码,因为行数较少,但谢谢!我希望这也能成为其他人的好榜样!
      猜你喜欢
      • 1970-01-01
      • 2012-07-18
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      相关资源
      最近更新 更多