【问题标题】:Array of dates from current date [duplicate]当前日期的日期数组[重复]
【发布时间】:2019-05-21 08:51:48
【问题描述】:

美好的一天。

我一直在尝试在 Laravel 中使用 Carbon 获取当天的日期。所以如果今天是 12 月 20 日,我想得到一个数组:

December 20, 2018
December 21, 2018
December 22, 2018
December 23, 2018
December 24, 2018

我想做 2 周甚至 3 周。这是我目前得到的。

$currentdate = Carbon::now()->format('m/d/Y');
$ts = strtotime($currentdate);

$year = date('o', $ts);
$week = date('W', $ts);

$datearray = [];
for($i = 1; $i <= 7; $i++) {
   $ts = strtotime($year.'W'.$week.$i);
   array_push($datearray,date("m/d/Y", $ts));
}

上面的代码给了我从一周开始的一周,而不是从以后的一天。

【问题讨论】:

  • Carbon 有一些很好的获取和设置日期的方法,例如 addDay() 和 toDateString。它可能比你在这里尝试做的更容易。查看他们的docs here
  • 在循环中使用碳addDays(1);,由于某种原因,您在旧版 strtotime 中混音

标签: php laravel date php-carbon


【解决方案1】:

如果您已经在使用Carbon,请使用它的强大功能!

use \Carbon\Carbon;

// how many days you want in your array
$count = 7;
$dates = [];
$date = Carbon::now();
for ($i = 0; $i < $count; $i++) {
    $dates[] = $date->addDay()->format('F d, Y');
}

// Show me what you got
print_r($dates);

输出是:

Array
(
    [0] => December 22, 2018
    [1] => December 23, 2018
    [2] => December 24, 2018
    [3] => December 25, 2018
    [4] => December 26, 2018
    [5] => December 27, 2018
    [6] => December 28, 2018
)

【讨论】:

    【解决方案2】:

    试试这个,

    $datearray = [];
    for($i = 0; $i < 7; $i++) {
       array_push($datearray, date('F d, Y', strtotime($i == 0 ?'today UTC':'today +'.$i.'day')));
       //push to array as 'December 20, 2018'
    }
    

    享受编码吧~! :)

    【讨论】:

    • 为什么使用 carbon 忽略它所有的方法并恢复到 strtotime?
    • @tim,它有很多有用的内置函数,比 PHP Data 的原始函数更容易开发。:) carbon.nesbot.com/docs"
    • 没错,那么为什么不使用它们呢?
    • @tim,如果你想要更高的性能,你可以在你的代码中使用它,内置函数还包括 PHP 方法在内部:)
    • 如果这就是您认为为什么要使用 Carbon::now 的原因?你不能同时拥有它。
    猜你喜欢
    • 1970-01-01
    • 2017-09-09
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多