【问题标题】:Calculate a date range according to the current date根据当前日期计算日期范围
【发布时间】:2020-01-07 12:06:16
【问题描述】:

我已经在这个网站上搜索了我需要的东西,但我找不到任何我想要的东西。我在从 mysql 中提取两个日期之间的数据时有点困难。我知道系统如何编写代码来过滤两个日期之间的数据,但我遇到的问题是这两个日期在不同的月份。让我进一步解释;

我有工作代码来提取两个日期之间的日期 - 目前我必须手动设置它们。

我需要的是根据当前日期计算两个日期($from & $till)。 $from 应始终为一个月的 25 号 (00:00),$till 应为下个月的 24 号 (23:59),而当前日期应始终介于两者之间。

示例: 2020 年 1 月 7 日,$from 应为 2019 年 12 月 25 日 00:00,$till 应为 2020 年 1 月 24 日 (23:59) 2020 年 1 月 25 日,$from 应为 2020 年 1 月 25 日 00:00,$till 应为 2020 年 2 月 24 日 (23:59)

目前我有以下代码,我手动设置日期:

<?php 

    $from = strtotime('25/12/2019 00:00');
    $till = strtotime('24/01/2020 23:59');

    $stmt = $con -> prepare("SELECT SUM(`amount`) as `total` 
                            FROM `income` 
                            WHERE user_id = ? 
                            && time >= ? && time <= ?"); 
    $stmt -> bind_param('iii', $user_id, $from, $till); 
    $stmt -> execute(); 
    $stmt -> store_result(); 
    $stmt -> bind_result($total_income); 
    $stmt -> fetch();

?>

那么有没有办法根据当前时间自动设置这些日期呢?

【问题讨论】:

  • 这能回答你的问题吗? How do I query between two dates using MySQL?
  • 你真的是在问如何根据当前日期自动生成开始日期和结束日期?
  • 另外 $strtotime('25/12/2019 00:00') 将返回 'false'
  • 我已经搜索了这个网站,但我找不到我的问题的答案。这就是为什么我解释了我的情况
  • 那么你可以提出这个问题的主题 :) 所以现在你必须告诉我们根据今天的日期计算 2 个日期的规则是什么

标签: php mysql date


【解决方案1】:

要自动设置日期(根据当前日期),您可以这样做:

//default: from 25th of last month to 24th of current month
$from = strtotime('-1 month',strtotime(date('m/25/Y 00:00:00')));
$till = strtotime(date('m/24/Y 23:59:59'));

if (intval(date('d')) > 24) { //current day is bigger than 25 - shift it one month
    $from = strtotime('+1 month',$from);
    $till = strtotime('+1 month',$till);
}

这将使用上个月的 25 日作为默认开始日期,并将当月 24 日作为默认结束日期。

如果当前日期已经是该月的 25 号(或更晚),则这两个日期都会偏移 1 个月。

另外:如果您在日期中使用斜线,请记住格式是月/日/年,而不是日/月/年

【讨论】:

  • 在这个问题的上下文中,我只是不认为这是有用的
  • @Strawberry 这个问题有点混乱,这可能就是答案。 See this commentthis answer
  • 对——问题(最后一句)是:那么有没有办法根据当前时间自动设置这些日期?
  • 谢谢布雷。您是说 if 子句中的 from 和 until 而不是 start 和 end 吗?
  • @yedek:对 - 我只有 $start 和 $end,然后将其更改为 $from 和 $till 以反映您的代码 - 错过了这两个。
猜你喜欢
  • 1970-01-01
  • 2017-05-16
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多