【问题标题】:List of all remaining months after specific date - PHP特定日期后所有剩余月份的列表 - PHP
【发布时间】:2016-06-03 16:52:16
【问题描述】:

我需要列出当月 15 日之后的所有剩余月份。

例如如果今天是 6 月 15 日,剩下的月份是 7 月、8 月、9 月、10 月、11 月、12 月。

我不想存储月数,在数据库表中分配一个 ID,因为那样效率不高。

我如何在 PHP 中做到这一点?

到目前为止,我已经关注了当前月份。

$todaysmonth= date('F');

我是否跟随嵌套的 IF?还是有更好的办法?

【问题讨论】:

  • 创建一个包含所有月份的数组。在数组中搜索当前月份并从数组中切出剩余的月份。
  • 可以得到当前日期的月份,之后就可以得到接下来的月份...

标签: php date


【解决方案1】:

从日期中获取当前月份编号,并循环获取月份名称。

$todaysmonth = date('n', strtotime("15 June 2016"));
for($i = $todaysmonth; $i <= 12; $i++){
    $dateObj   = DateTime::createFromFormat('!m', $i);
    echo $monthName = $dateObj->format('F');
}

Working Example

【讨论】:

    【解决方案2】:

    在这里,我们将使用 DatePeriod,它允许在一组日期和时间上进行迭代,在给定的时间段内定期重复。

    所以我们得到了结束日期和开始日期,然后计算了间隔。然后循环遍历我们得到月份数组的时间段。

    // current date : 20 Feb 2019
    
     $startDate = new \DateTime('first day of next month');
     $endDate = new \DateTime('1st january next year');
    
     $interval = new \DateInterval('P1M');
     $period = new \DatePeriod($startDate, $interval, $endDate);
    
     // Start array with current date
    $dates = [];
    
    // Add all remaining dates to array
    foreach ($period as $date) {
         array_push($dates, $date->Format('F'));
    }
    
    // output
    print_r($dates); die;
    
    Array ( [0] => March [1] => April [2] => May [3] => June [4] => July 
    [5] => August [6] => September [7] => October [8] => November [9] => 
    December )
    

    【讨论】:

    • 请补充说明
    • 这里我们将使用 DatePeriod,它允许在一组日期和时间上进行迭代,在给定的时间间隔内定期重复。所以我们得到了结束日期和开始日期,然后计算了间隔。然后循环遍历我们得到月份数组的时间段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 2020-10-12
    • 2015-04-18
    • 1970-01-01
    相关资源
    最近更新 更多