[英]how to get wednesday date between two dates in php
need to obtain all wednesday dates between two dates. 需要获取两个日期之间的所有星期三日期。 For ex start and end date= 对于前开始日期和结束日期=
01/07/2019 - 01/25/2019
expected result= 预期结果=
01/09/2019,
01/16/2019,
01/23/2019
can i use if ($startDate->format('w') == 2) {}
condition to filter wednesdays and push into array. 我可以使用if ($startDate->format('w') == 2) {}
条件来过滤星期三并推入数组。 any method to get the result? 有什么方法可以得到结果吗?
Use DatePeriod Class . 使用DatePeriod类 。 date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period. 日期时间段允许在给定时间段内按固定的时间间隔在一组日期和时间上进行迭代。
$period = new DatePeriod(
new DateTime($date1),
new DateInterval('P1D'),
new DateTime($date2)
);
$cnt = 0;
foreach ($period as $key => $value) {
if($value->format('D') == 'Wed'){
$wed[$cnt] = $value->format('m/d/Y');
$cnt++;
}
}
Output 输出量
[0] => 01/09/2019
[1] => 01/16/2019
[2] => 01/23/2019
<?php
$from_date ='01/07/2019';
$to_date ='01/25/2019';
$from_date = new DateTime($from_date);
$to_date = new DateTime($to_date);
$get_date = array();
for ($date = $from_date; $date <= $to_date; $date->modify('+1 day')) {
if($date->format('l') == 'Wednesday'){
$get_date[] = $date->format('m/d/Y');
}
}
print_r($get_date);
Out put 放出
Array ( [0] => 01/09/2019 [1] => 01/16/2019 [2] => 01/23/2019 )
You will get the required output. 您将获得所需的输出。
<?php
$date1 = date("01/07/2019");
$date2 = date("01/25/2019");
$day1 = date('D', strtotime($date1));
$period = new DatePeriod(New Datetime($date1),New DateInterval('P1D'),New DateTime($date2));
$cnt = 0;
foreach($period as $key => $value ){
if($value->format('D') == 'Wed'){
$wed[$cnt] = $value->format('m/d/Y');
echo $wed[$cnt];
$cnt++;
echo '<BR>';
}
}
?>
Using the base DateTime
class and instead of checking every day, just keep adding 7 days to the date and check if it is still less than the end date. 使用基本的DateTime
类,而不是每天检查,只需继续在日期上添加7天,然后检查日期是否仍小于结束日期。 The only additional logic is that if the start date is a Wednesday, then use this date, otherwise get the next Wednesday... 唯一的附加逻辑是,如果开始日期是星期三,则使用该日期,否则获取下一个星期三...
$fromDate = new DateTime('01/02/2019');
if ( $fromDate->format('D') != 'Wed') {
$fromDate->modify("next wednesday");
}
$toDate = new DateTime('01/25/2019');
do {
echo $fromDate->format("m/d/Y").PHP_EOL;
}
while ( $fromDate->modify(""+7 day"") < $toDate );
outputs... 输出...
01/02/2019
01/09/2019
01/16/2019
01/23/2019
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.