设置特定年份PHP的第一周

时间:2015-03-18 19:52:22

标签: php date datetime

我想将一个日期设置为first week of the year,我将传递给函数作为参数。我的意思是如果我的日期是03/18/2015,我希望将此日期设置为一年中的第一周,结果应为:12/31/2014(这是第一次约会的第一周[03/18 / 2015])。这是我尝试的代码,但是当更改日期的年份给我一年或第一周的下一周时:

$actualDate = new DateTime("03/18/2015");
$actualDate = setFirstWeekOfYear($actualDate);

function setFirstWeekOfYear( $currentDate )
{
    // this variable will contain the current week number
    $currentWeek = $currentDate->format("W");

    // Get the current year (2015 in this moment)
    $currentYear = $currentDate->format("Y");

    // Rest the weeks number to the current date
    $currentDate = $currentDate->modify("-{$currentWeek} week");

    return $currentDate;
}

// 03/18/2017 => the output is 12/31/2016
// 03/18/2015 => the output should be 12/31/2014 but what i'm getting is 12/24/2014

注意:2017年3月18日的日期运作良好,但2015年3月18日给我一周的第一周。我正在将java Calendar.WEEK_OF_YEAR, 1函数作为参考

提前致谢:)

2 个答案:

答案 0 :(得分:2)

DateTime类了解ISO周编号,因此您可以执行以下操作: -

function getFirstWeekOfYear(\DateTime $date = null)
{
    if(!$date){
        $date = new \DateTime();
    }
    return (new \DateTime())->setISODate((int)$date->format('o'), 1, $date->format('w'));
}

你应该注意到第01周的ISO 8601定义是一年中第一个星期四的那一周 1

A working example

1:ISO week date
2:PHP date format strings

我不是Java程序员,但谷歌的一点点谷歌搜索告诉我Java不使用ISO周数,所以可能会给你错误的结果。 This question and answers may help you further.

答案 1 :(得分:0)

通过对http://writecodeonline.com/php/进行一些测试......我发现如果你做了:

$currentWeek = $currentDate->format("W") - 1; // subtract 1

这将产生第31个作为日期...我认为推理与不想包含 $actualDate的当前周这一事实有关。 EG:如果2015年3月18日=第12周......在第12周前减去11周。

尝试一下,也许这对你有用吗?


更新(修订)


查看评论以获得解释:

$actualDate = new DateTime("03/18/2016");
$actualDate = setFirstWeekOfYear($actualDate);

function setFirstWeekOfYear($currentDate)
{
  // Grab year of current date
  $currentYear = $currentDate->format("Y");

  // Make a new DateTime variable and set the date
  $date = new DateTime();
  $date->setISODate($currentYear, 1, -1);

  // This should give you the Monday of the
  // first week that the year starts on
  return $date;
}

// 03/19/2018 = Saturday, December 30, 2017
// 03/19/2017 = Saturday, December 31, 2016
// 03/19/2016 = Saturday, January 02, 2016
// 03/19/2015 = Saturday, December 27, 2014
// 03/19/2014 = Saturday, December 28, 2013
echo $actualDate->format("l, F d, Y");
相关问题