Get Week Numbers between two dates in php - php

I want to get the week numbers for given two dates i.e from 2012-01-01 to 2012-12-31.The week numbers should fall exactly in the range as specified above.Can u please give suggestions for doing this.

Something like this should work fine:
<?php
$startDateUnix = strtotime('2012-01-01');
$endDateUnix = strtotime('2013-01-01');
$currentDateUnix = $startDateUnix;
$weekNumbers = array();
while ($currentDateUnix < $endDateUnix) {
$weekNumbers[] = date('W', $currentDateUnix);
$currentDateUnix = strtotime('+1 week', $currentDateUnix);
}
print_r($weekNumbers);
?>
DEMO.
Output:
Array
(
[0] => 52
[1] => 01
[2] => 02
.........
[51] => 51
[52] => 52
)

I think you want something like this using DateTime:
$first_date = new DateTime();
$last_date = new DateTime('-50 weeks');
$days_array = array();
foreach(new DatePeriod($first_date, new DateInterval('P1D'), $last_date) as $date) {
$days_array[] = $date->format('W');
}

Something like this should do the job:
$start = '2012-01-01';
$end = '2012-12-31';
$dates = range(strtotime($start), strtotime($end),604800);
$weeks = array_map(function($v){return date('W', $v);}, $dates); // Requires PHP 5.3+
print_r($weeks);

Do something like this:
[REMOVED]
EDIT
<?php
for($w = strtotime($start_date); $w <= strtotime($end_date); $w += 7 * 24 * 3600)
{
echo date("W", $w) . '<br />';
}
?>

You can get the number of weeks between two dates using the weeks_between_dates() function below.
function weeks_between_dates($d1,$d2)
{
$t1 = strtotime($d1);
$t2 = strtotime($d2);
$out = array();
while ($now <= $t2) {
$out[] = date('W', $t1);
$t1 = strtotime('+1 week', $t1);
}
return $out;
}
print_r( weeks_between_dates('2015-01-01','2015-12-31') ); // 01..53
print_r( weeks_between_dates('2016-01-01','2016-12-31') ); // 01..52

Related

Split date ranges into corresponding weeks

I have date ranges called from and to.I want to convert it to weeks.
Suppose from date is 1-10-2014 and to date is 31-10-2014
Then result is:
1st week : 01-10-2014 to 04-10-2014
2nd : 05-102014 to 11-10-2014
3rd : 12-10-2014 to 18-10-2014
4th : 19-10-2014 to 25-10-2014
5th : 26-10-2014 to 31-10-2014
In php.I try several code but that didn't given the absolute result only give 01 to 7 , 8 to 14 etc.
Pls help.
I already try answers from
Get the date of one week from today with PHP in stack overflow
date("Y-m-d",strtotime("+1 week"));
This snippet uses Sunday as the first day of the week:
$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++;
}
}
Each week will have all the days in it.
If you just want the first and last days of each week then you can just use array_shift and array_pop to get them. For example, for the first week you can use:
$wk1Start = array_shift($weeks[1]); //gives you first day of week 1
$wk1End = array_pop($weeks[1]); // give you the last day of week 1
If you want the start and end dates for each week, here is a way of doing it:
$ranges = array_map(function($week) {
return 'start: ' . array_shift($week)
. ', end: ' . array_pop($week); },
$weeks);
This is the output of $ranges for me:
Array
(
[1] => start: 2014-10-01, end: 2014-10-04
[2] => start: 2014-10-05, end: 2014-10-11
[3] => start: 2014-10-12, end: 2014-10-18
[4] => start: 2014-10-19, end: 2014-10-25
[5] => start: 2014-10-26, end: 2014-10-31
)
You can easily change the week starting day (set to Monday at the moment):
$fromDate = '2018-05-03';
$toDate = '2018-08-11';
$result = getWeekRanges($fromDate, $toDate);
array_walk_recursive($result, 'applyFormat');
echo '<pre>';
print_r($result);
echo '</pre>';
function getWeekRanges($start, $end) {
$timeStart = strtotime($start);
$timeEnd = strtotime($end);
$out = [];
$milestones[] = $timeStart;
$timeEndWeek = strtotime('next Monday', $timeStart);
while ($timeEndWeek < $timeEnd) {
$milestones[] = $timeEndWeek;
$timeEndWeek = strtotime('+1 week', $timeEndWeek);
}
$milestones[] = $timeEnd;
$count = count($milestones);
for ($i = 1; $i < $count; $i++) {
if( $i == $count - 1) {
$out[] = [
'start' => $milestones[$i - 1],
'end' => $milestones[$i]
];
}else{
$out[] = [
'start' => $milestones[$i - 1],
'end' => $milestones[$i] - 1
];
}
}
return $out;
}
function applyFormat(&$item) {
$item = date('Y-m-d', $item);
}
Try
$start_date = date('Y-m-d', strtotime('2014-10-01'));
$end_date = date('Y-m-d', strtotime('2014-10-31'));
$i=1;
for($date = $start_date; $date <= $end_date; $date = date('Y-m-d', strtotime($date. ' + 7 days'))) {
echo getWeekDates($date, $start_date, $end_date, $i);
echo "\n";
$i++;
}
function getWeekDates($date, $start_date, $end_date, $i) {
$week = date('W', strtotime($date));
$year = date('Y', strtotime($date));
$from = date("Y-m-d", strtotime("{$year}-W{$week}+1")); //Returns the date of monday in week
if($from < $start_date) $from = $start_date;
$to = date("Y-m-d", strtotime("{$year}-W{$week}-7")); //Returns the date of sunday in week
if($to > $end_date) $to = $end_date;
echo "$i th ".$from." to ".$to.'<br>';
}
output :-
1 th 2014-10-01 to 2014-10-05
2 th 2014-10-06 to 2014-10-12
3 th 2014-10-13 to 2014-10-19
4 th 2014-10-20 to 2014-10-26
5 th 2014-10-27 to 2014-10-31

php check multiple dates in array are within a date range

I have an array structured like this:
Array ( [0] => 24-12-2013 [1] => 25-12-2013 [2] => 26-12-2014 [3] => 27-12-2013 [4])
I would like to check if any of the dates in the array are within a given date range.
The date range is structured like this:
$start = (date("d-m-Y", strtotime('25-12-2013')));
$end = (date("d-m-Y", strtotime('26'12'2013')));
I would like to know which dates in the array are within the date range.
Couple things:
Use timestamps or DateTime objects to compare dates, not strings
Use date format YYYY-MM-DD to avoid potential ambiguity about your date format (d/m/y or m/d/y)
This code will do what you want:
$dates = array("2013-12-24","2013-12-25","2014-12-24","2013-12-27");
$start = strtotime('2013-12-25');
$end = strtotime('2013-12-26');
foreach($dates AS $date) {
$timestamp = strtotime($date);
if($timestamp >= $start && $timestamp <= $end) {
echo "The date $date is within our date range\n";
} else {
echo "The date $date is NOT within our date range\n";
}
}
See it in action:
http://3v4l.org/GWJI2
$dates = array ('24-12-2013', '25-12-2013', '26-12-2014', '27-12-2013');
$start = strtotime('25-12-2013');
$end = strtotime('26-12-2013');
$inDateRange = count(
array_filter(
$dates,
function($value) use($start, $end) {
$value = strtotime($value);
return ($value >= $start && $value <= $end);
}
)
);
<?php
$start = DateTime::createFromFormat('d-m-Y', '25-12-2013');
$end = DateTime::createFromFormat('d-m-Y', '26-12-2013');
$dates = array('24-12-2013','25-12-2013','26-12-2014','27-12-2013');
$matches = array();
foreach ($dates as $date) {
$date2 = DateTime::createFromFormat('d-m-Y', $date);
if ($date2 >= $start && $date2 =< $end) {
$matches[] = $date;
}
}
print_r($matches);
See it in action
$_between = array();
$start = date('Ymd', strtotime($start));
$end = date('Ymd', strtotime($end));
foreach ($dates as $date)
{
$date = date('Ymd',strtotime($date));
if ($date > $start && $date < $end) {
array_push($_between,$date);
continue;
}
}
echo '<pre>';
var_dump($_between);
echo '</pre>';
Loop over the array turning each date into unix time (seconds since Jan 1, 1970), and do simple math to see if the number of seconds is between the range. Like so:
$start = strtotime('25-12-2013');
$end = strtotime('26'12'2013');
foreach($date in $dates) {
$unix_time = strtotime($date);
if($unix_time > $start && $unix_time < $end)
//in range
}
// PHP >= 5.3:
$dates_in_range = array_filter($array, function($date) {
global $start;
global $end;
return (strtotime($date) >= strtotime($start) and strtotime($date) <= strtotime($end));
});

PHP - Get dates of next 5 weekdays?

I'm trying to create an array of the next 5 working week days (Monday - Friday, excluding today). I know the working week varies around the world but this is not important for what I am trying to do.
So, for example, if today is a Wednesday, I want the dates for Thursday and Friday of the current week and Monday, Tuesday and Wednesday of the following week.
I thought this would work:
$dates = array();
for ($i = 1; $ < 6; $i ++)
{
$dates[] = date('Y-m-d', strtotime('+ '.$i.' weekday'));
}
But for today, it is giving me:
Monday 1st
Tuesday 2nd
Wednesday 3rd
Thursday 4th
Sunday 7th!
Any advice appreciated.
Thanks
Try this
$dates = array();
$date = new DateTime();
while (count($dates)<5)
{
$date->add(new DateInterval('P1D'));
if ($date->format('N')<6)
$dates[]=$date->format('Y-m-d');
}
function getWeekdayDatesFrom($format, $start_date_epoch, $end_date_epoch, $range) {
$dates_arr = array();
if( ! $range) {
$range = round(abs($start_date_epoch-$end_date_epoch)/86400) + 1;
} else {
$range = $range + 1; //end date inclusive
}
$current_date_epoch = $start_date_epoch;
for($i = 1; $i <= $range; $i+1) {
$d = date('N', $current_date_epoch);
if($d <= 5) { // not sat or sun
$dates_arr[] = "'".date($format, $current_date_epoch)."'";
}
$next_day_epoch = strtotime('+'.$i.'day', $start_date_epoch);
$i++;
$current_date_epoch = $next_day_epoch;
}
return $dates_arr;
}
This should work:
$dates = array();
$i = 0;
while(true) {
$i++;
$time = strtotime("+$i days");
$dayOfWeek = date('w', $time);
/* 'w' - day of week, numeric, i.e. "0" (Sunday) to "6" (Saturday) */
if( ($dayOfWeek == 0) or ($dayOfWeek == 6) ) {
continue;
}
$dates[] = date('Y-m-d', $time);
if( count($dates) >= 5 ) {
break;
}
}
You can do like this:
$now = time();
$day = 60*60*24;
$days = array();
for ($i=1; $i<=7; $i++){
$ts = $now + $day*$i;
if (date("N", $ts) < 6){
$days[] = date("l jS", $ts);
}
}
The output for the above code is:
Array(
[0] => Monday 1st
[1] => Tuesday 2nd
[2] => Wednesday 3rd
[3] => Thursday 4th
[4] => Friday 5th
)

Get mondays tuesdays etc

How can I echo all dates for mondays/ wednesday / friday between these two dates?
This is what I have been working with:
function get_days ( $s, $e )
{
$r = array ();
$s = strtotime ( $s . ' GMT' );
$e = strtotime ( $e . ' GMT' );
$day = gmdate ( 'l', $s );
do
{
$r[] = $day . ', ' . gmdate ( 'Y-m-d', $s );
$s += 86400 * 7;
} while ( $s <= $e );
return $r;
}
print_r ( get_days ( $start, $end ) );
Try this:
function getDates($start_date, $end_date, $days){
// parse the $start_date and $end_date string values
$stime=new DateTime($start_date);
$etime=new DateTime($end_date);
// make a copy so we can increment by day
$ctime = clone $stime;
$results = array();
while( $ctime <= $etime ){
$dow=$ctime->format("w");
// assumes $days is array containing integers for Sun (0) - Sat (6)
if( in_array($dow, $days) ){
// make a copy to return in results
$results[]=clone $ctime;
}
// incrememnt by 1 day
//$ctime=date_add($ctime, date_interval_create_from_date_string('1 days'));
$ctime->modify("+1 days");
}
return $results;
}
// get every Tues, Wed, Fri from now to End of June
getDates('2011-06-15','2011-06-30',array(2,3,5));
You should be able to get the days using strtotime(). It accepts arguments like next Tuesday and also parses 2011-06-15 into a correct timestamp. And yes, you need one (or more) loop(s).
This should be sufficient to point you in the right direction.
Ok, you updated your question while I was writing my answer. You can't assume that a day always has 86400 seconds. When DST starts or ends your assumption will be incorrect.
<?php
$start = "1 Jan 2011";
$end = "20 Jan 2011";
$dates = getDays($start, $end);
print_r($dates);
function getDays($start,$end)
{
$t = new DateTime("$start 12:00");
$e = new DateTime($end ." 12:00");
$out = array();
for (; $t<=$e; $t->modify("+1 day")) {
$day = $t->format("D");
if (in_array($day, array('Mon','Wed','Fri'))) {
$out[] = $t->format('d M Y');
}
}
return $out;
}

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

I'm starting with a date 2010-05-01 and ending with 2010-05-10. How can I iterate through all of those dates in PHP?
$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d H:i:s\n");
}
This will output all days in the defined period between $start and $end. If you want to include the 10th, set $end to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod. It requires PHP 5.3.
This also includes the last date
$begin = new DateTime( "2015-07-03" );
$end = new DateTime( "2015-07-09" );
for($i = $begin; $i <= $end; $i->modify('+1 day')){
echo $i->format("Y-m-d");
}
If you dont need the last date just remove = from the condition.
Converting to unix timestamps makes doing date math easier in php:
$startTime = strtotime( '2010-05-01 12:00' );
$endTime = strtotime( '2010-05-10 12:00' );
// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
$thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc
}
When using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping or repeating.
Copy from php.net sample for inclusive range:
$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
echo $date->format("Ymd") . "<br>";
}
Here is another simple implementation -
/**
* Date range
*
* #param $first
* #param $last
* #param string $step
* #param string $format
* #return array
*/
function dateRange( $first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
$dates = [];
$current = strtotime( $first );
$last = strtotime( $last );
while( $current <= $last ) {
$dates[] = date( $format, $current );
$current = strtotime( $step, $current );
}
return $dates;
}
Example:
print_r( dateRange( '2010-07-26', '2010-08-05') );
Array (
[0] => 2010-07-26
[1] => 2010-07-27
[2] => 2010-07-28
[3] => 2010-07-29
[4] => 2010-07-30
[5] => 2010-07-31
[6] => 2010-08-01
[7] => 2010-08-02
[8] => 2010-08-03
[9] => 2010-08-04
[10] => 2010-08-05
)
$startTime = strtotime('2010-05-01');
$endTime = strtotime('2010-05-10');
// Loop between timestamps, 1 day at a time
$i = 1;
do {
$newTime = strtotime('+'.$i++.' days',$startTime);
echo $newTime;
} while ($newTime < $endTime);
or
$startTime = strtotime('2010-05-01');
$endTime = strtotime('2010-05-10');
// Loop between timestamps, 1 day at a time
do {
$startTime = strtotime('+1 day',$startTime);
echo $startTime;
} while ($startTime < $endTime);
User this function:-
function dateRange($first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
Usage / function call:-
Increase by one day:-
dateRange($start, $end); //increment is set to 1 day.
Increase by Month:-
dateRange($start, $end, "+1 month");//increase by one month
use third parameter if you like to set date format:-
dateRange($start, $end, "+1 month", "Y-m-d H:i:s");//increase by one month and format is mysql datetime
For Carbon users
use Carbon\Carbon;
$startDay = Carbon::parse("2021-08-01");
$endDay= Carbon::parse("2021-08-05");
$period = $startDay->range($endDay, 1, 'day');
When I print the data
[
Carbon\Carbon #1627790400 {#4970
date: 2021-08-01 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1627876800 {#4974
date: 2021-08-02 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1627963200 {#4978
date: 2021-08-03 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1628049600 {#5007
date: 2021-08-04 00:00:00.0 America/Toronto (-04:00),
},
Carbon\Carbon #1628136000 {#5009
date: 2021-08-05 00:00:00.0 America/Toronto (-04:00),
},
]
This is Laravel data dump using dd($period->toArray());. You can now iterate through $period if you want with a foreach statement.
One important note - it includes both the edge dates provided to method.
For more cool date related stuff, do check out the Carbon docs.
here's a way:
$date = new Carbon();
$dtStart = $date->startOfMonth();
$dtEnd = $dtStart->copy()->endOfMonth();
$weekendsInMoth = [];
while ($dtStart->diffInDays($dtEnd)) {
if($dtStart->isWeekend()) {
$weekendsInMoth[] = $dtStart->copy();
}
$dtStart->addDay();
}
The result of $weekendsInMoth is array of weekend days!
If you're using php version less than 8.2 and don't have the DatePeriod::INCLUDE_END_DATE const. I wrote a method that returns an array of \DateTimeImmutable.
This works with a start date before, the same or after the end date.
/**
* #param DateTimeImmutable $start
* #param DateTimeImmutable $end
* #return array<\DateTimeImmutable>
*/
public static function getRangeDays(\DateTimeImmutable $start, \DateTimeImmutable $end): array
{
$startDate = $start;
$endDate = $end;
$forwards = $endDate >= $startDate;
$carryDate = $startDate;
$days = [];
while (true) {
if (($forwards && $carryDate > $end) || (!$forwards && $carryDate < $end)) {
break;
}
$days[] = $carryDate;
if ($forwards) {
$carryDate = $carryDate->modify('+1 day');
} else {
$carryDate = $carryDate->modify('- 1 day');
}
}
return $days;
}
$date = new DateTime($_POST['date']);
$endDate = date_add(new DateTime($_POST['date']),date_interval_create_from_date_string("7 days"));
while ($date <= $endDate) {
print date_format($date,'d-m-Y')." AND END DATE IS : ".date_format($endDate,'d-m-Y')."\n";
date_add($date,date_interval_create_from_date_string("1 days"));
}
You can iterate like this also, The $_POST['date'] can be dent from your app or website
Instead of $_POST['date'] you can also place your string here "21-12-2019". Both will work.
<?php
$start_date = '2015-01-01';
$end_date = '2015-06-30';
while (strtotime($start_date) <= strtotime($end_date)) {
echo "$start_daten";
$start_date = date ("Y-m-d", strtotime("+1 days", strtotime($start_date)));
}
?>
If you use Laravel and want to use Carbon the correct solution would be the following:
$start_date = Carbon::createFromFormat('Y-m-d', '2020-01-01');
$end_date = Carbon::createFromFormat('Y-m-d', '2020-01-31');
$period = new CarbonPeriod($start_date, '1 day', $end_date);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d H:i:s\n");
}
Remember to add:
use Carbon\Carbon;
use Carbon\CarbonPeriod;

Categories