dongwen3093 2017-07-27 23:43
浏览 11
已采纳

选择首先出现的日期或日期

I am trying to pick either Friday / Saturday or 3rd, 18th, 30th, 31st... which ever comes first.

Real example: Current date is Tuesday, January 10th, 2017.

Options:

  1. Friday, January 13th 2017
  2. Wednesday, January 18th 2017

My code should pick the Friday, January 13th 2017.

PHP

$dayOfWeekArray  = ['friday', 'saturday'];
$dayOfMonthArray = [3, 18, 30, 31];

foreach ($dayOfWeekArray as $dayOfWeek) {
    $nextDayDate = new DateTime("next $dayOfWeek");

    foreach ($dayOfMonthArray as $dayOfMonth) {
        # Continue if $nextDayDate is before, or equals, whichever date $dayOfMonth turns out to be.

        # Otherwise, determine which comes first, $nextDayDate or $dayOfMonth
    }
}

Question: How can I turn $dayOfMonth into a date?

  • 写回答

2条回答 默认 最新

  • duanfu4446 2017-07-28 00:08
    关注

    I would use DatePeriod to loop through days at an interval of 1 day until the formatted date matches one of the values you are looking for —

    $start = new \DateTime("2017-01-10");
    
    // You can probably do some math to determine the minimum number needed here
    
    // php version 7.1.5 
    // $end = (clone $start)->modify("+31 days");
    
    // php version 5.6
    $end = clone $start;
    $end->modify("+31 days");
    
    $interval = new \DateInterval("P1D"); // An interval of 1 day
    $period = new \DatePeriod($start, $interval, $end);
    
    foreach ($period as $date) {
        if (in_array($date->format('l'), ['Friday', 'Saturday']) || in_array((int) $date->format('d'), [3, 18, 30, 31])) {
            break;
        }
    }
    
    echo $date->format('l, Y-m-d') ;
    
    // outputs 'Friday, 2017-01-13'
    

    I think you’re asking that the final date not be 2017-01-13 if the current day is already 2017-01-13 — in which case you can just add a day to the start day, like $start = (new \DateTime("today"))->modify("+1 day")

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算