how to get sunday date between two date - php

I try this
<?php
$startdate = '2016-07-15';
$enddate = '2016-07-17';
$sundays = [];
$startweek=date("W",strtotime($startdate));
$endweek=date("W",strtotime($enddate));
$year=date("Y",strtotime($startdate));
for($i=$startweek;$i<=$endweek;$i++) {
$result=$this->getWeek($i,$year);
if($result>$startdate && $result<$enddate) {
$sundays[] = $result;
}
}
print_r($sundays);
public function getWeek($week, $year)
{
$dto = new \DateTime();
$result = $dto->setISODate($year, $week, 0)->format('Y-m-d');
return $result;
}
?>
this return blank array. but in between two dates 2016-07-17 is Sunday.
I get output as 2016-07-17
I refer this here
But in this link return output as no of sunday not date.

Give this a try:
$startDate = new DateTime('2016-07-15');
$endDate = new DateTime('2016-07-17');
$sundays = array();
while ($startDate <= $endDate) {
if ($startDate->format('w') == 0) {
$sundays[] = $startDate->format('Y-m-d');
}
$startDate->modify('+1 day');
}
var_dump($sundays);
If you want later to use the DateTime objects instead of the formatted date, then you must use DateTimeImmutable for the $startDate variable:
$startDate = new DateTimeImmutable('2016-07-15');
$endDate = new DateTimeImmutable('2016-07-17');
$sundays = array();
while ($startDate <= $endDate) {
if ($startDate->format('w') == 0) {
$sundays[] = $startDate;
}
$startDate->modify('+1 day');
}
var_dump($sundays);

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);
}
$dateArr = getDateForSpecificDayBetweenDates('2010-01-01', '2010-12-31', 0);
print "<pre>";
print_r($dateArr);
Try out this code..

Try this
$start = new DateTime($startDate);
$end = new DateTime($endDate);
$sundays = [];
while ($start->getTimestamp() != $end->getTimestamp()) {
if ($start->format('w') == 0) {
$sundays[] = $start->format('Y-m-d');
}
$start->add('+1 DAY');
}

This will return you all sundays between two dates.
$startdate = '2016-05-1';
$enddate = '2016-05-20';
function getSundays($start, $end) {
$timestamp1 = strtotime($start);
$timestamp2 = strtotime($end);
$sundays = array();
$oneDay = 60*60*24;
for($i = $timestamp1; $i <= $timestamp2; $i += $oneDay) {
$day = date('N', $i);
// If sunday
if($day == 7) {
// Save sunday in format YYYY-MM-DD, if you need just timestamp
// save only $i
$sundays[] = date('Y-m-d', $i);
// Since we know it is sunday, we can simply skip
// next 6 days so we get right to next sunday
$i += 6 * $oneDay;
}
}
return $sundays;
}
var_dump(getSundays($startdate, $enddate));

Use Carbon
$arrayOfDate = [];
$startDate = Carbon::parse($startDate)->modify('this sunday');
$endDate = Carbon::parse($endDate);
for ($date = $startDate; $date->lte($endDate); $date->addWeek()) {
$arrayOfDate[] = $date->format('Y-m-d');
}
return $arrayOfDate;

Related

Transform PHP script to a general-case function

I have this code that modify date in the way I want, for example, if starting date is 31/01/2000, adding 1 month will return 29/02/2000, then, 31/03/2000.
If date is 30/01/2000 (not last day of the month) it will return 29/02/2000, then 30/03/2000, 30/04/2000 and so on.
I want to transfirm that code in a general case function, to be able to add 1,3,6,12 months, and inside the for loop, to work all corect.
I would like it to be a function 2 or 3 arguments, startingDate, duration(nr of iterations), frequency (add 1/3/6/12 months per once).
<?php
$date = new DateTime('2000-01-28'); // or whatever
#echo $date->format('d')." ".$date->format('t');
$expectedDay = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y');
for ($i = 0; $i < 100; $i++) {
echo $date->format('Y-m-d') . "<br>";
if ($month++ == 12) {
$year++;
$month = 1;
}
$date->modify("${year}-${month}-1");
if ($expectedDay > $date->format('t')) {
$day = $date->format('t');
} else {
$day = $expectedDay;
}
$date->modify("${year}-${month}-${day}");
}
Whelp, there's an extremely easy function for this in PHP nowadays.
first, you get a timestamp instead of a datetime:
$timestamp = $date->getTimestamp();
Now, just use strtotime to add onto the date.
strtotime("+1 month", $myTimestamp);
You can change the +1 into anything you want, so you just throw the amount in the string and voila; a dynamic way of adding them!
however, since you want to do +30 days instead of a natural month, you're better off just adding 30 days to the timestamp, like so:
$timestamp = $timestamp + (3600 * 24 * 30); //s per h * h per d * d
So, you'd end up with something like this:
function calculateTime($startingDate, $iterations, $frequency){
$timeStamp = strtotime($startingDate);//if you expect a string date
$timeToAdd = (3600 * 24 * 30) * $frequency; //30 days * frequency
$return = array();
$return[] = date('Y-m-d', $timeStamp); //Original date
$previousDate = $timeStamp; //Original date for now
for($i = 0; $i < $iterations; $i++){
$newDate = $previousDate + (3600 * 24 * 30);
$return[] = date('Y-m-d', $newDate);
$previousDate = $newDate;
}
return $return;
}
And then for the rendering part:
//Let's render this stuff
$dates = calculateTime('24-08-2017', 25, 3);
foreach($dates as $date){
echo "$date</br>";
}
If you'd like to do it with full months, something like this:
<?php
function calculateTime($startingDate, $iterations, $frequency){
$timeStamp = strtotime($startingDate);//if you expect a string date
$return = array();
$return[] = date('Y-m-d', $timeStamp); //Original date
$previousDate = $timeStamp; //Original date for now
for($i = 0; $i < $iterations; $i++){
$lastDay = false;
//It's the last day of the month
if(date('t', $timeStamp) == date('d', $timeStamp)){
$lastDay = true;
}
if($frequency == 12){
$newDate = strtotime('+1 year', $previousDate);
}
else{
if($lastDay){
$firstDayOfMonth = strtotime(date("01-m-Y", $previousDate));
$newDate =strtotime("+$frequency month", $firstDayOfMonth);
}
else{
$newDate = strtotime("+$frequency month", $previousDate);
}
}
if($lastDay){
$return[] = date('Y-m-t', $newDate);
}
else{
$return[] = date('Y-m-d', $newDate);
}
$previousDate = $newDate;
}
return $return;
}
//Let's render this stuff
$dates = calculateTime('31-01-2000', 25, 1);
foreach($dates as $date){
echo "$date</br>";
}
I hope this helps? :)
If you'd like to see how this works quickly, just paste my code into a phpfiddle. Unfortunately the save function is broken right now.

Extract only date from datetime for calculating total time in PHP

I have date time data in database and from that im calculating total hours only taking the date not the timing.
im using strtotime for that calculations. For ex:
$LastDate = '2016-04-27 17:27:28';
$endDate = strtotime($LastDate); // 1461770848
$LastDate = '2016-04-27';
$endDate = strtotime($LastDate); // 1461708000
I want this second value only.
So i want to extract the date from the $LastDate .
///////////Getting data from Employee Outstation(Travel) details from database/////////////
$employeeTravel = new EmployeeTravelRecord();
$TravelEntryList = $employeeTravel->Find("employee = 2 and (date(travel_date) <= ? and ? <= date(return_date))",array($req['date_end'],$req['date_start']));
$startdate = $req['date_start'];
$enddate = $req['date_end'];
foreach($TravelEntryList as $Travelentry){
$key = $Travelentry->employee;
if($startdate >= $Travelentry->travel_date)
{
$firstdate = $startdate;
}
else
$firstdate = $Travelentry->travel_date;
if($enddate <= $Travelentry->return_date )
{
$lastdate = $enddate;
}
else
$lastdate = $Travelentry->return_date;
$holidays = $this->getholidays($firstdate,$lastdate);
$totalhours = $this->getWorkingDays($firstdate,$lastdate,$holidays);
$amount = $totalhours;
}
private function getWorkingDays($FirstDate,$LastDate,$holidays){
$endDate = strtotime($LastDate); //Here i want to give only date not the time
$startDate = strtotime($FirstDate);
$days = ($endDate - $startDate) / 86400 + 1;
$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);
//Im doing even and odd saturday calculations....finally...
$workinghours = $workingDays*9 + $no_saturdays*7;
return $workinghours;
}
such expression gives you desired result
echo strtotime('midnight', strtotime('2016-04-27 22:11')); // 1461715200
echo strtotime('2016-04-27'); // 1461715200

How can I calculate date weekend in php

I have a date like this
$start = strtotime('2010-01-01'); $end = strtotime('2010-01-25');
My question:
How can I calculate or count weekend from $start & $end date range..??
A more modern approach is using php's DateTime class. Below, you get an array with week numbers as keys. I added the counts of weeks and weekend days.
<?php
$begin = new DateTime('2010-01-01');
$end = new DateTime('2010-01-25');
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval, $end);
$weekends = [];
foreach($daterange as $date) {
if (in_array($date->format('N'), [6,7])) {
$weekends[$date->format('W')][] = $date->format('Y-m-d');
}
}
print_r($weekends);
echo 'Number of weeks: ' . count($weekends);
echo 'Number of weekend days: ' . (count($weekends, COUNT_RECURSIVE) - count($weekends));
Note: if you're using PHP 5.3, use array() instead of block arrays [].
May be this code snippet will help:
<?php
//get current month for example
$beginday = date("Y-m-01");
$lastday = date("Y-m-t");
$nr_work_days = getWorkingDays($beginday, $lastday);
echo $nr_work_days;
function getWorkingDays($startDate, $endDate)
{
$begin = strtotime($startDate);
$end = strtotime($endDate);
if ($begin > $end) {
echo "startdate is in the future! <br />";
return 0;
} else {
$no_days = 0;
$weekends = 0;
while ($begin <= $end) {
$no_days++; // no of days in the given interval
$what_day = date("N", $begin);
if ($what_day > 5) { // 6 and 7 are weekend days
$weekends++;
};
$begin += 86400; // +1 day
};
$working_days = $no_days - $weekends;
return $working_days;
}
}
Another solution can be: (Get date range between two dates excluding weekends)
This might help maybe:
$start = strtotime('2010-01-01');
$end = strtotime('2010-01-25');
$differ = $end-$start;
$min = $differ/60;
$hrs = $min/60;
$days = $hrs/24;
$weeks = $days/7;
if(is_int($weeks))
$weeks++;
echo '<pre>';
print_r(ceil($weeks));
echo '</pre>';

PHP loop - add days to date

I have the following code. It works to add days (daysBetween) to a date (startDate). However, I want to REPEAT it until it reaches the end date. How can I do this??
$startDate = "2009-10-11";
$endDate = "2010-01-20";
$daysBetween = 10;
function addDayswithdate($date,$days){
$date = strtotime("+".$days." days", strtotime($date));
return date("Y-m-d", $date);
}
$date = addDayswithdate($startDate,$daysBetween);
You can use following function;
<?php
$startDate = "2009-10-11";
$endDate = "2010-01-20";
$daysBetween = 10;
$finalResult = array();
function addDayswithdate($date,$days, $endDate, &$finalResult){
$tempDate = strtotime($date);
$tempDate += 3600*24*$days;
if ($tempDate < strtotime($endDate)) {
$finalResult[] = date("Y-m-d", $tempDate);
addDayswithdate(date("Y-m-d", $tempDate), $days, $endDate, $finalResult);
} else {
return true;
}
}
addDayswithdate($startDate,$daysBetween, $endDate, $finalResult);
var_dump($finalResult);
Here is a working demo: Demo
function addDayswithdate($from, $to, $interval){
$result = array();
while(true)
{
$dateTemp = strtotime("+".$interval." days", strtotime($from));
if(strtotime($dateTemp) > strtotime($to))
break;
$result[] = date("Y-m-d", $dateTemp);
$interval += $interval;
}
return $result;
}

PHP: List of days between two dates [duplicate]

This question already has answers here:
PHP: Return all dates between two dates in an array [duplicate]
(26 answers)
Closed 4 years ago.
Is there an easy way to get a list of days between two dates in PHP?
I would like to have something like this in the end:
(pseudocode)
date1 = 29/08/2013
date2 = 03/09/2013
resultArray = functionReturnDates(date1, date2);
and the resulting array would contain:
resultArray[0] = 29/08/2013
resultArray[1] = 30/08/2013
resultArray[2] = 31/08/2013
resultArray[3] = 01/09/2013
resultArray[4] = 02/09/2013
resultArray[5] = 03/09/2013
for example.
$date1 = '29/08/2013';
$date2 = '03/09/2013';
function returnDates($fromdate, $todate) {
$fromdate = \DateTime::createFromFormat('d/m/Y', $fromdate);
$todate = \DateTime::createFromFormat('d/m/Y', $todate);
return new \DatePeriod(
$fromdate,
new \DateInterval('P1D'),
$todate->modify('+1 day')
);
}
$datePeriod = returnDates($date1, $date2);
foreach($datePeriod as $date) {
echo $date->format('d/m/Y'), PHP_EOL;
}
function DatePeriod_start_end($begin,$end){
$begin = new DateTime($begin);
$end = new DateTime($end.' +1 day');
$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);
foreach($daterange as $date){
$dates[] = $date->format("Y-m-d");
}
return $dates;
}
dunno if this is at all practical, but it works pretty straight-forward
$end = '2013-08-29';
$start = '2013-08-25';
$datediff = strtotime($end) - strtotime($start);
$datediff = floor($datediff/(60*60*24));
for($i = 0; $i < $datediff + 1; $i++){
echo date("Y-m-d", strtotime($start . ' + ' . $i . 'day')) . "<br>";
}
Try this:
function daysBetween($start, $end)
$dates = array();
while($start <= $end)
{
array_push(
$dates,
date(
'dS M Y',
$start
)
);
$start += 86400;
}
return $dates;
}
$start = strtotime('2009-10-20');
$end = strtotime('2009-10-25');
var_dump(daysBetween($start,$end));
$datearray = array();
$date = $date1;
$days = ceil(abs($date2 - $date1) / 86400) + 1;//no of days
for($i = 1;$i <= $days; $i++){
array_push($datearray,$date);
$date = $date+86400;
}
foreach($datearray as $days){
echo date('Y-m-d, $days);
}

Categories