【问题标题】:Calculate the first day of next month and quarter from today in PHP用PHP计算从今天起下个月和下季度的第一天
【发布时间】:2021-09-03 15:58:52
【问题描述】:

从今天开始计算下个月的第一天:

$firstDayNextMonth = date('Y-m-d', strtotime('first day of next month'));

如何计算从今天起下个季度的第一天?

  • 第一季度,第一季度:1 月 1 日 - 3 月 31 日
  • 第二季度,第二季度:4 月 1 日至 6 月 30 日
  • 第三季度,第三季度:7 月 1 日至 9 月 30 日
  • 第四季度,第四季度:10 月 1 日至 12 月 31 日

谢谢!

【问题讨论】:

  • 你的季度什么时候开始?
  • 对我来说它们是 传统上这些被称为“四分之一天”并且已经使用了几个世纪。他们的日期是 - 3 月 25 日(女士节)、6 月 24 日(仲夏节)、9 月 29 日(迈克尔马斯)和 12 月 25 日(圣诞节)。
  • @RiggsFolly 我已将季度日期添加到我的问题中。谢谢。

标签: php


【解决方案1】:

可能有更优雅的方法,但这可以解决问题

$today = '2021-12-03';

$now = new DateTimeImmutable($today);
$nowMonth = (int) $now->format('m');
$yr = (int) $now->format('Y');

# Next quarter
echo 'Todays date is ' . $now->format('d/m/Y').PHP_EOL;
switch ($nowMonth){
    case 1:
    case 2:
    case 3:
        $quarter = new DateTimeImmutable("$yr/04/01");
        echo 'Next quarter is ' . $quarter->format('d/m/Y') . PHP_EOL;
        break;
    case 4:
    case 5:
    case 6:
        $quarter = new DateTimeImmutable("$yr/07/01");
        echo 'Next quarter is ' . $quarter->format('d/m/Y') . PHP_EOL;
        break;
    case 7:
    case 8:
    case 9:
        $quarter = new DateTimeImmutable("$yr/10/01");
        echo 'Next quarter is ' . $quarter->format('d/m/Y') . PHP_EOL;
        break;
    case 10:
    case 11:
    case 12:
        $yr++;
        $quarter = new DateTimeImmutable("$yr/01/01");
        echo 'Next quarter is ' . $quarter->format('d/m/Y') . PHP_EOL;
        break;
}

【讨论】:

    【解决方案2】:

    由于不同人的宿舍可能不同,我认为你需要在代码中定义你的宿舍是什么。

    那么这只是判断当前季度以及下一季度是否是新年的情况:

    //define our quarters
    $quarters = array(
    1 => '01-01',
    2 => '04-01',
    3 => '07-01',
    4 => '10-01'
    );
    
    $month = date("n"); //get current month as a number
    
    $currentQuarter = ceil($month / 3); //get the current quarter
    
    echo 'We are currently in Q'.$currentQuarter.' of '.date("Y")."\n";
    
    $nextQuarter = $currentQuarter+1;
        
    //check if our quarter is defined, if not it is probably '5' which means next year
    if (!isset($quarters[$nextQuarter])) { 
        $nextQuarter = 1;
        $year = date("Y")+1;
    } else {
        $year = date("Y");
    }
    
    echo 'The first day of the next quarter is '.date("Y-m-d", strtotime($year.'-'.$quarters[$nextQuarter]));
    

    这是一个工作示例:https://3v4l.org/2Mo4o

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2023-02-13
      相关资源
      最近更新 更多