Date object start from Monday - php

I currently split a date range into weeks using the following function, and it works great. The only probelm is the week starts from Sunday. Is there a way of modifying it so it starts from Monday?
$start = new DateTime('2014-10-01');
$end = new DateTime('2014-10-31 23:59');
$interval = new DateInterval('P1D');
$dateRange = new DatePeriod($start, $interval, $end);
$weekNumber = 1;
$weeks = array();
foreach ($dateRange as $date) {
$weeks[$weekNumber][] = $date->format('Y-m-d');
if ($date->format('w') == 6) {
$weekNumber++;
}
}

$dow = ($date->format('w') + 6) % 7;
% gives you the remainder after dividing by 7. So, $dow will be 0 for Monday (not Sunday) and 6 will be Sunday (not Saturday).

Related

find cout of specific day between two date php without using any loop?

I need to find out count of a specific Day between two date.
I can do this by using loop between two date, but if there is difference of 10 years(suppose) between date loop will run 10*365 times.
Is any easier way to do this?
Thanks in advance
function countDays($day, $start, $end)
{
$start = strtotime($start);
$end = strtotime($end);
$datediff = $end - $start;
$days = floor($datediff / (60 * 60 * 24));
//get the day of the week for start and end dates (0-6)
$w = array( date('w', $start ), date('w', $end) );
//get partial week day count
if ($w[0] < $w[1])
{
$partialWeekCount = ($day >= $w[0] && $day <= $w[1]);
}else if ($w[0] == $w[1])
{
$partialWeekCount = $w[0] == $day;
}else
{
$partialWeekCount = ($day >= $w[0]
$day <= $w[1]);
}
//first count the number of complete weeks, then add 1 if $day falls in a partial week.
return intval($days / 7) + $partialWeekCount;
}
Function Call - countDays( 5, "2017-04-14", "2017-04-21")
You are looking for date_diff() function. The date_diff() function returns the difference between two DateTime objects.
<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>
To find occurrence of specific day (for eg: Sunday). Please note: I have used 7 for Sunday. You can use 1 for Monday, 2 for Tuesday and so on
$cnt = 0;
$start = new DateTime("2013-03-15");
$end = new DateTime("2013-12-12");
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt)
{
if ($dt->format('N') == 7)
{
$cnt++;
}
}
echo $cnt;

PHP: Loop through all weeks in a date range (last 2 years)?

I like to iterate through all weeks in a date range that spawns 2 years. Starting at the current week number two years ago, until the current week number this year.
The problem is that a year can either have 52 weeks or 53 weeks, for example:
2015 had 53 weeks (the 53th was from 2015-12-28 till 2016-01-03)
2016 had 52 weeks (the 52th was from 2016-12-26 till 2017-01-01)
So this is currently my php code:
# start with the current week 2 years ago
$year = date("Y") - 2;
$week = (int) date("W"); // (int) removes leading zero for weeks < 10
$endYear = date("Y");
$endWeek = (int) date("W");
# iterate through all weeks until now
do {
echo $week. " of ". $year;
$week++;
if ($week > 52) { // or greater 53 ?????????????
$year ++;
$week = 1;
}
}
while ($year < $endYear || $week < $endWeek);
Instead of trying to keep track of the bounds, let PHP do it for you.
$start = new DateTime('-2 years');
$end = new DateTime();
$interval = new DateInterval('P1W');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
echo $date->format('W') . " of ". $date->format('Y') . "\n";
}
Demo
With the help of Ross Wilson and John Conde I found a solution:
$now = new DateTime;
$from = (new DateTime)->setISODate($now->format('Y') - 2, $now->format('W'));
$from->modify("thursday this week"); // see ISO 8601
while($from < $now) {
echo $from->format('W Y').'<br />';
$from->modify("+1 week");
}
It is important so set the week day to thursday, because according to ISO 8601, the week "belongs" to the year which still contains the thursday.
You could use DateTime and setISODate for something like this:
$now = new DateTime;
$from = (new DateTime)->setISODate($now->format('Y') - 2, $now->format('W'));
while($from < $now) {
echo $from->format('W Y').'<br />';
$from->modify("1 week");
}
Hope this helps!

find out how many weekend in a date range

for example I have two dates 2015-10-28 and 2015-12-31. from these I want to know how many saturday and sunday in that given date range. I can find the diff between that dates but I can't find how many weekends.
anyone ever made this?
here is my current code:
function createDateRange($maxDate, $cell, $lead, $offArray = array()){
$dates = [];
--$cell;
--$lead;
$edate = date('Y-m-d', strtotime($maxDate." -$lead day"));
$sdate = date('Y-m-d', strtotime($edate." -$cell day"));
$start = new DateTime($sdate);
$end = new DateTime($edate);
$end = $end->modify('+1 day');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach($period as $d){
$dt = $d->format('Y-m-d');
if(!in_array($dt, $dates)){
$dates[] = $dt;
}
}
return $dates;
}
basically I want to add sat+sun count to the date range.
The trick is to use an O(1)-type algorithm to solve this.
Given your starting date, move to the first Saturday. Call that from
Given your ending date, move back to the previous Friday. Call that to
Unless you have an edge case (where to is less than from), compute (to - from) * 2 / 7 as the number of weekend days, and add that to any weekend days passed over in steps (1) and (2).
This is how I do it in production, although generalised for arbitrary weekend days.
Use this function:
function getDateForSpecificDayBetweenDates($startDate, $endDate, $weekdayNumber)
{
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
$dateArr = array();
do
{
if(date("w", $startDate) != $weekdayNumber)
{
$startDate += (24 * 3600); // add 1 day
}
} while(date("w", $startDate) != $weekdayNumber);
while($startDate <= $endDate)
{
$dateArr[] = date('Y-m-d', $startDate);
$startDate += (7 * 24 * 3600); // add 7 days
}
return($dateArr);
}
The function call to get dates for all Sunday's in year 2015:
$dateArr = getDateForSpecificDayBetweenDates('2015-01-01', '2015-12-31', 0);
print "<pre>";
print_r($dateArr);
//周日0 周一1 .....
$data = 4;//周四
$t1 ='2015-10-28';
$t2 = '2015-12-31';
$datetime1 = date_create($t1);
$datetime2 = date_create($t2);
$interval = date_diff($datetime1, $datetime2);
$day = $interval->format('%a');
$result = ($day)/7;
$start = getdate(strtotime($t1))['wday'];
$end = getdate(strtotime($t2))['wday'];
if($data>=$start && $data<=$end){
echo floor($result)+1;
}else{
echo floor($result);
}

Add datetime Value

I'm searching for the best way to echo day numbers in a week.
First i need to check what week there is.
And then echo all dates of the week into variables.
This is what i got:
//This Week Variable dates
$this_year = date('Y');
$this_week_no = date('W');
$this_week_mon = new DateTime();
$this_week_mon->setISODate($this_year,$this_week_no);
How do i rise tue by one day?
$this_week_tue = $this_week_mon ++;
You can use DateTime::modify():
$this_week_mon->modify('+1 day');
or DateTime::add() which accepts a DateInterval() object:
$this_week_mon->add(new DateInterval('P1D'));
You can loop through all of the days of the week using DatePeriod():
$start = new DateTime();
$start->setISODate($this_year,$this_week_no);
$end = clone $start;
$end->modify('+1 week');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
echo $date->format('N');
}
$this_week_mon->modify('+1 day');
Should increment $this_week_mon by one day. To increase by more, just use days;
$this_week_mon->modify('+27 day');
Would increment by 27 days.

PHP: DatePeriod with last day of month

I'd like to work with PHP DateInterval to iterate through months:
$from = new DateTime();
$from->setDate(2014, 1, 31);
$period = new DatePeriod($from, new DateInterval('P1M'), 12);
I'd expect it to returns 31 January, 28 February (as the DateInterval is 1 month), but it actually returns 31 January, 3 March, 3 of April... hence skipping February.
Is there any way to do this simply?
Thanks!
EDIT : as a refernece, here is a solution that seems to cover most use cases:
$date = new DateTime('2014-01-31');
$start = $date->format('n');
for ($i = 0; $i < 28; $i++) {
$current = clone $date;
$current->modify('+'.$i.' month');
if ($current->format('n') > ($start % 12) && $start !== 12) {
$current->modify('last day of last month');
}
$start++;
echo $current->format('Y-m-d').PHP_EOL;
}
You can use DateTime::modify():
$date = new DateTime('last day of january');
echo $date->format('Y-m-d').PHP_EOL;
for ($i = 1; $i < 12; $i++) {
$date->modify('last day of next month');
echo $date->format('Y-m-d').PHP_EOL;
}
EDIT: I think I didn't understand your question clearly. Here is a new version:
$date = new DateTime('2014-01-31');
for ($i = 0; $i < 12; $i++) {
$current = clone $date;
$current->modify('+'.$i.' month');
if ($current->format('n') > $i + 1) {
$current->modify('last day of last month');
}
echo $current->format('Y-m-d').PHP_EOL;
}
The issue is cause by the variance between the last day in each of the months within the range. ie. February ending on 28 instead of 31 and the addition of 1 month from the last day 2014-01-31 + 1 month = 2014-03-03 https://3v4l.org/Y42QJ
To resolve the issue with DatePeriod and simplify it a bit, adjust the initial date by resetting the specified date to the first day of the specified month, by using first day of this month.
Then during iteration, you can modify the date period date by using last day of this month to retrieve the bounds of the currently iterated month.
Example: https://3v4l.org/889mB
$from = new DateTime('2014-01-31');
$from->modify('first day of this month'); //2014-01-01
$period = new DatePeriod($from, new DateInterval('P1M'), 12);
foreach ($period as $date) {
echo $date->modify('last day of this month')->format('Y-m-d');
}
Result:
2014-01-31
2014-02-28
2014-03-31
2014-04-30
2014-05-31
2014-06-30
2014-07-31
2014-08-31
2014-09-30
2014-10-31
2014-11-30
2014-12-31
2015-01-31
Then to expand on this approach, in order to retrieve the desired day from the specified date, such as the 29th. You can extract the specified day and adjust the currently iterated month as needed when the day is out of bounds for that month.
Example: https://3v4l.org/SlEJc
$from = new DateTime('2014-01-29');
$day = $from->format('j');
$from->modify('first day of this month'); //2014-01-01
$period = new DatePeriod($from, new DateInterval('P1M'), 12);
foreach ($period as $date) {
$lastDay = clone $date;
$lastDay->modify('last day of this month');
$date->setDate($date->format('Y'), $date->format('n'), $day);
if ($date > $lastDay) {
$date = $lastDay;
}
echo $date->format('Y-m-d');
}
Result:
2014-01-29
2014-02-28 #notice the last day of february is used
2014-03-29
2014-04-29
2014-05-29
2014-06-29
2014-07-29
2014-08-29
2014-09-29
2014-10-29
2014-11-29
2014-12-29
2015-01-29
You may try like this:
$date = new DateTime();
$lastDayOfMonth = $date->modify(
sprintf('+%d days', $date->format('t') - $date->format('j'))
);
I would do it probably like this
$max = array (
31,28,31,30,31,30,31,31,30,31,30,31
); //days in month
$month = 1;
$year = 2014;
$day = 31;
$iterate = 12;
$dates = array();
for ($i = 0;$i < $iterate;$i++) {
$tmp_month = ($month + $i) % 12;
$tmp_year = $year + floor($month+$i)/12;
$tmp_day = min($day, $max[$tmp_month]);
$tmp = new DateTime();
$tmp->setDate($tmp_year, $tmp_month + 1, $tmp_day);
$dates[] = $tmp;
}
var_dump($dates);
This keeps to the same day each month if possible

Categories