繁体   English   中英

使用星期和年份获取一个月中的某一天的问题

[英]Issue with getting the day of a month with the week day and year

我正在尝试使用此代码获取一个月中的某一天:

// your input
$month      = "September";
$year       = "2013";
$dayWeek    = "Friday";
$week       = 2;

// create a date object
$date = new DateTime();

// set to the first day of the specified year/month
$date->modify($year . '-' . $month . '-01');

// add $week -1 weeks to the date
$date->modify('+' . ($week - 1) . ' week');

// set to day of week
$date->modify($dayWeek);

// here's the day of month for you
echo $date->format('j');

但是这段代码不起作用,为什么不呢?

因为如果我有这个数据:

$month      = "December";
$year       = "2019";
$dayWeek    = "saturday";
$week       = 2;

它应该返回 07,因为如果我们查看 2019 年 12 月的日历......第一周就是星期日,但它返回 14,我想知道为什么? 如果 12 月 14 日在第三周..

我想知道或得到一个代码,它给了我一个月中的哪一天……只是给了 $month, $year, dayWeek 和一个月的一周。

这里

当您指定dayname日期时,引用:

移至此名称的第二天。

所以,

$date->modify($year . '-' . $month . '-01');

给你 2019 年,12 月 1 日,也就是星期日

$date->modify('+' . ($week - 1) . ' week');

增加 1 周,现在的日期是 12 月 8 日,星期日

$date->modify($dayWeek);

查找下一个星期六,即 12 月 14 日,正好是本月的第二个星期六。

这可能会解决您的问题。

<?php
// your input
$month      = "December";
$year       = "2019";
$dayWeek    = "saturday";
$week       = 2;


// create a date object
$date = new DateTime();

$date->modify($year . '-' . $month . '-01');

$date->modify('sunday');  // Put here 'saturday' if your week ends with saturday and starts with sunday

$end_of_the_first_week = $date->format('j');

// Start over again
$date->modify($year . '-' . $month . '-01');

$date->modify($dayWeek);

if ($date->format('j') > $end_of_the_first_week) { // we already in the second week
  if ($week > 2) { 
    // add $week -2 weeks to the date
    $date->modify('+' . ($week - 2) . ' week');
  }
} else if ($week > 1) {
    // add $week -1 weeks to the date
    $date->modify('+' . ($week - 1) . ' week');
}

echo $date->format('j'); // 7 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM