Get mondays tuesdays etc - php

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;
}

Related

Get whole week date starting from sunday to saturday from given date

Hello guys i am working in php and my requirement is to get complete week dates from given date as i need to calculate weekly working hour. And week must be started from sunday to saturday not monday to sunday. I have code which works properly for other days of week except sunday. it means if give any dates from monday to saturday it works properly but if i give sunday's date it give last week's dates. please check my code and advise me for better solution.
$days = array();
$ddate = "2018-01-07";
$date = new DateTime($ddate);
$week = $date->format("W");
$y = date("Y", strtotime($ddate));
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
Using the DateTime, DateInterval and DatePeriod classes you could do it like this perhaps
function getperiod( $start ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval('P1D'),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ 7days' ) ) )
);
}
$start='2018-01-07';
$period=getperiod( $start );
foreach( $period as $date ){
echo $date->format('l -> Y-m-d') . '<br />';
}
Which returns
Sunday -> 2018-01-07
Monday -> 2018-01-08
Tuesday -> 2018-01-09
Wednesday -> 2018-01-10
Thursday -> 2018-01-11
Friday -> 2018-01-12
Saturday -> 2018-01-13
Or, by modifying the parameters of the getperiod function you can make that function far more flexible.
function getperiod( $start, $interval='P1D', $days=7 ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval( $interval ),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ '.$days.' days' ) ) )
);
}
$start='2018-01-07';
$days=array();
$period=getperiod( $start );
foreach( $period as $date ){
$days[]=$date->format('Y-m-d');
}
echo '<pre>',print_r($days,true),'</pre>';
For instance: To find every Sunday for the next year
$period=getperiod( $start,'P7D', 365 );
foreach( $period as $date ){
$days[]=$date->format('Y-m-d');
}
echo '<pre>',print_r($days,true),'</pre>';
To ensure that the calculations begin on a Sunday which has a numeric value of 7
function getperiod( $start, $interval='P1D', $days=7 ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval( $interval ),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ '.$days.' days' ) ) )
);
}
/* A date from which to begin calculations */
$start='2018-01-01';
/* Array to store output */
$days=array();
/* integer to represent which day of the week to operate upon */
$startday = 7;
/* Output format for resultant dates */
$output='Y-m-d';
/* Calculate initial startdate given above variables */
$start=date( DATE_COOKIE, strtotime( $start . ' + ' . ( $startday - date( 'N', strtotime( $start ) ) ) . ' days' ) );
/* Get the period range */
$period=getperiod( $start );
foreach( $period as $date ){
/* store output in desired format */
$days[]=$date->format( $output );
}
/* do something with data */
echo '<pre>',print_r($days,true),'</pre>';
From source,
Here is the snippet you are looking for,
// set current date
$date = '01/03/2018';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400){
print date("m/d/Y l", $ts) . "\n";
}
Here is working demo.
If you need normal standard format code,
Here is your snippet,
// set current date
$date = '2018-01-03';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset * 86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400) {
print date("Y-m-d l", $ts) . "\n";
}
Here is working demo.
EDIT
As per your requirement, now week will start from sunday to saturday
<?php
// set current date
$date = '2018-01-03';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Sunday
$dow = date('w', $ts);
$offset = $dow;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Sunday
$ts = $ts - $offset * 86400;
// loop from Sunday till Saturday
for ($i = 0; $i < 7; $i++, $ts += 86400) {
print date("Y-m-d l", $ts) . "\n";
}
<?php
$days = array();
$ddate = "2018-01-07";
$y = date("Y", strtotime($ddate));
if(date("l", strtotime($ddate))=='Sunday'){
$ddate = date("Y-m-d ", strtotime($ddate. "+1 day"));
}
$date = new DateTime($ddate);
$week = $date->format("W");
echo "<br/>";
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
?>
try this:
$days = array();
$ddate = "2018-01-07";
$date = new DateTime($ddate);
$week = $date->format("N")==7?$date->modify("+1 week")->format("W"):$date->format("W");
$y = date("Y", strtotime($ddate));
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
$dto = new DateTime();
$year = date_create($this->week_date)->format('o');
$week_no = date('W', strtotime($this->week_date));
$dto->setISODate($year, $week_no);
$dto->modify('-1 days');
$ret['sunday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['monday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['tuesday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['wednesday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['thursday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['friday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['saturday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['next_sunday'] = $dto->format('Y-m-d');

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

Get Week Numbers between two dates in 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

Get day names between two date in PHP

How to get name of days between two dates in PHP?
Input:
Start Date: 01-01-2013
End date: 05-01-2013
Output:
Tuesday
Wednesday
Thursday
Friday
Saturday
Tried code
$from_date ='01-01-2013';
$to_date ='05-01-2013';
$number_of_days = count_days(strtotime($from_date),strtotime($to_date));
for($i = 1; $i<=$number_of_days; $i++)
{
$day = Date('l',mktime(0,0,0,date('m'),date('d')+$i,date('y')));
echo "<br>".$day;
}
function count_days( $a, $b )
{
$gd_a = getdate( $a );
$gd_b = getdate( $b );
$a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] );
$b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] );
return round( abs( $a_new - $b_new ) / 86400 );
}
I saw the post Finding date of particular day between two dates PHP
But I don't got my result
Please help me
Use the DateTime class, it will be much more simple:
$from_date ='01-01-2013';
$to_date ='05-01-2013';
$from_date = new DateTime($from_date);
$to_date = new DateTime($to_date);
for ($date = $from_date; $date <= $to_date; $date->modify('+1 day')) {
echo $date->format('l') . "\n";
}
$from_date ='01-01-2013';
$to_date ='05-01-2013';
$start = strtotime($from_date);
$end = strtotime($to_date);
$day = (24*60*60);
for($i=$start; $i<= $end; $i+=86400)
echo date('l', $i);
<?php
function printDays($from, $to) {
$from_date=strtotime($from);
$to_date=strtotime($to);
$current=$from_date;
while($current<=$to_date) {
$days[]=date('l', $current);
$current=$current+86400;
}
foreach($days as $key=> $day) {
echo $day."\n";
}
}
$from_date ='01-01-2013';
$to_date ='05-01-2013';
printDays($from_date, $to_date);
?>
Loop through every day between the given dates (inclusive) and then add the corresponding day in an array, using date function. Print out the array and tada! you're done!

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