Laravel中的碳日期格式

时间:2017-04-10 20:32:22

标签: laravel php-carbon

我有一个碳对象数组被传递到这样的视图:

return view('booking.choose-days')->with(['weekDays' => $weekDays]);

为了测试一切正常,我已经对数组进行了DD检查,看到正确传递了日期数组:

array:14 [▼
  0 => Carbon {#252 ▼
    +"date": "2017-04-11 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "Europe/London"
  }
  1 => Carbon {#257 ▼
    +"date": "2017-04-12 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "Europe/London"
  }
  2 => Carbon {#256 ▼
    +"date": "2017-04-13 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "Europe/London"
  }
  3 => Carbon {#255 ▼
    +"date": "2017-04-14 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "Europe/London"
  }

...and so forth

使用以下内容循环遍历Blade中的数组时(完整的html遗漏):

@foreach ($weekDays as $key => $weekDay)
    <tr id="{{ $key }}">
      <td>
        {{ $weekDay }}
      </td>
    </tr>
@endforeach

这会产生预期的输出:

2017-04-11 00:00:00

2017-04-12 00:00:00

2017-04-13 00:00:00

2017-04-14 00:00:00

2017-04-15 00:00:00

...and so forth

然而,当输出时:

@foreach ($weekDays as $key => $weekDay)
    <tr id="{{ $key }}">
      <td>
        {{ $weekDay->dayOfWeek }} // now accessing a property
      </td>
    </tr>
@endforeach

我得到了输出:

1
1
2
2
2

而不是1,2,3,4,5等预期的Monday, Tuesday, Wednesday

因此,当var_dumpedobjects时,数组中的日期是正确的,但是当访问dayOfWeek这样的属性时,它会给我不正确的属性。

通过首先阅读网址two timestamps - start dateend date来生成日期。然后将这两个值存储在变量中并发送到函数以删除所有周末日期。

这是对函数的调用:

$weekDays = getWeekDays(Carbon::createFromTimestamp($startDate), Carbon::createFromTimestamp($endDate));

这是功能:

function getWeekDays(Carbon $startDate, Carbon $endDate)
{
    for($date = $startDate; $startDate->lte($endDate); $startDate->addDay()) {
        if ($date->isWeekDay()) {
            $weekdays[] = clone $date;
        }
    }

    return $weekdays;
}

知道为什么吗?

由于

1 个答案:

答案 0 :(得分:0)

您好试试这段代码:

 @foreach ($weekDays as $key => $weekDay)
<tr id="{{ $key }}">
  <td>
    {{    \Carbon\Carbon::parse($weekDay)->format('d/m/Y')->dayOfWeek }} // now accessing a property
  </td>
</tr>
 @endforeach
相关问题