Addition of time type column - php

I don't know how to add time
WrokController
if($request->status === 'completed')
{
$t = 0;
$alltime = Work::where('project_id', $project->id)->get();
foreach($alltime as $time)
{
$t = $t + $time->work_time;
}
$project -> fill(['total_work_time' => $t])->save();
}
But isn't there a good way to do this?

You can sum it with interval,
$base_time = new DateTime();
$time_now = clone $base_time;
foreach ($alltime as $time) {
$array = explode(':', $time);
$base_time->add(new DateInterval(sprintf('PT%dH%dM', $array[0], $array[1])));
}
$sum_of_diff = $time_now->diff($base_time);

Related

PHP - ask user input for dates and pass to script

I have a php script here to create login at our datacenter for myself, but this script is doing the login for next week if i run it after 12:00 on monday, and a lot of times I'm not there the whole week, so I want to improve this script by asking for user input and pass the dates that I will be there so the script only picks up on those dates. I know i have to do this with stdin and I do have a part that works, but i have no idea on how to integrate this into the current script and how to make sure i can give multiple dates
My stdin part that does ask my for a date, but no idea on how to combine it:
<?php
function promptDateFromUser(string $prompt, string $dateFormat): DateTimeInterface
{
echo "{$prompt} [$dateFormat]: ";
$stdin = fopen('php://stdin', 'r');
$line = trim(fgets(STDIN));
fclose($stdin);
$dateTime = DateTimeImmutable::createFromFormat('Y-m-d', $line);
if (! $dateTime instanceof DateTimeInterface) {
throw new UnexpectedValueException('Invalid datetime format');
}
}
$dateTime = promptDateFromUser("Please insert date:", 'Y-m-d');
?>
My login script as of now:
<?php
require 'shared.php';
restore_exception_handler();
restore_error_handler();
$md = new RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$date = new DateTime();
$hour = (int)$date->format('H');
$dow = (int)$date->format('w');
if (($dow === 1 && $hour > 12) || ($dow > 1 && $dow < 6)) {
$add = 'P' . (8 - $dow) . 'D';
$date->add(new DateInterval($add));
}
if (($dow === 1 && $hour <= 12) || $dow === 0 || $dow === 6) {
if ($dow === 6) {
$date->add(new DateInterval('P2D'));
} elseif ($dow === 0 ) {
$date->add(new DateInterval('P1D'));
}
}
$tomorrow = $date->format('Y-m-d');
$duration = 720;
$customerId = 30;
$purpose = 'DCG visit';
$phoneNumber = '';
$name = 'SOME NAME, REMOVED FOR PUBLICATION';
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
for ($x = 0; $x < 5; $x++) {
$start = $tomorrow." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested for: ", $tomorrow, PHP_EOL;
$date->add(new DateInterval('P1D'));
$tomorrow = $date->format('Y-m-d');
}
?>
I'm a big php noob, so some explanation is greatly appreciated!
after some help from a friend, i managed to solve this:
#!/usr/bin/env php
<?php
include('shared.php');
restore_exception_handler();
restore_error_handler();
// Constants
$timeout = 45;
$md = new \RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$duration = "720";
$customerId = "30";
$purpose = "DCG visit";
$phoneNumber = "";
$name="SOME NAME, REMOVED FOR PUBLICATION";
// Functions
function requestInput($msg) {
global $timeout;
echo "$msg\n\nThe timeout for this selection is $timeout seconds.\n\n> ";
$fd = fopen('php://stdin', 'r');
$read = array($fd);
$write = $except = array(); // we don't care about this
if(stream_select($read, $write, $except, $timeout)) {
$choice = trim(fgets($fd));
}
echo "\nYou typed: $choice\n\n";
return $choice;
}
// Start of program
$date = new DateTime();
$weekchoice = (int)requestInput("Which week would you like to request access for?\n1) Current week\n2) Next week\n3) Specific week number");
if ($weekchoice == 3) {
$weeknumber = (int)requestInput("Please enter a numeric week number");
} else {
$weeknumber = (int)$date->format("W");
if ($weekchoice == 2) {
$weeknumber += 1;
}
}
// We override $date with the start of the chosen week
$date->setISODate($date->format("Y"), $weeknumber);
echo "Thanks, you chose week $weeknumber which starts with " . $date->format("l d F, Y") . " \n\n";
$dayschoice = requestInput("Please enter the days you want access, as a space separated list:\n1) Monday\n2) Tuesday\n3) Wednesday\n4) Thursday\n5) Friday\n\nExample: 1 3 5");
$daylist = explode(' ', $dayschoice);
$processedDays = [];
foreach ($daylist as $eachday) {
$iday = (int)$eachday;
if ($iday == 0 || $iday % 7 == 0) { // No Sundays, also (int)"" -> 0, which is terrible
continue;
}
$add_days = $iday - 1; // Sums 0 if Monday, 1 if Tuesday and so on...
$newdate = new DateTime($date->format("Y-m-d"));
$newdate->modify("+$add_days days");
$processedDays[] = $newdate;
$formatted = $newdate->format("l d F Y");
echo "Processing day $iday, which is $formatted\n";
}
$hour = $date->format('H');
$tomorrow = $date->format('Y-m-d');
$confirm = requestInput("\nRequest access for these days? Yes/No");
if ($confirm != "Yes") {
echo 'Good bye!';
exit(0);
}
foreach ($processedDays as $reqDay) {
echo "Submitting " . $reqDay->format("l d F Y") . "\n";
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
}
foreach ($processedDays as $reqDay) {
$start = $reqDay->format('Y-m-d')." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested: ", $reqDay->format('l d F Y'), PHP_EOL;
$tomorrow = $date->format('Y-m-d');
}
?>

Date Array For Every Day, Week, Month, Year in between 2 dates

I am trying to create an array using PHP OOP that basically creates and array for every day, month, year within 2 dates and allocates a ticket and hours worked set at 0 for every single day that has passed.
The code I have used is:
class statisticsClass{
private $DateFrom = null;
private $DateTo = null;
private $startYear = null;
private $startMonth = null;
private $startDay = null;
private $endYear = null;
private $endMonth = null;
private $endDay = null;
private $theDateDif = null;
private $stages = null;
private function makeDates(){
if(!empty($this->DateFrom)){
$this->DateFrom = $this->generals->convertDate($this->DateFrom);
} else {
$this->DateFrom = date('Y-m-d', strtotime('last year')) . ' 00:00:00';
}
if(!empty($this->DateTo)){
$this->DateTo = $this->generals->convertDate($this->DateTo);
} else {
$this->DateTo = date('Y-m-d', strtotime('now')) . ' 23:59:59';
}
list($theDate, $theTime) = explode(' ', $this->DateFrom);
list($this->startYear, $this->startMonth, $this->startDay) = explode('-', $theDate);
list($theDate2, $theTime2) = explode(' ', $this->DateTo);
list($this->endYear, $this->endMonth, $this->endDay) = explode('-', $theDate2);
}
private function removeZeros($number){
return ltrim($number, '0');
}
private function chartItemVersion(){
if($this->theDateDif <= 31){
$this->stages = 'daily';
} elseif($this->theDateDif > 31 && $this->theDateDif <= 183){
$this->stages = 'weekly';
} else {
$this->stages = 'monthly';
}
}
private function addZeros($number){
if($number < 10){
return '0' . $number;
}
return $number;
}
private function makingQueryArray(){
for($yearMake=$this->startYear; $yearMake<=$this->endYear; $yearMake++){
$this->queryArray[] = intval($yearMake);
}
foreach($this->queryArray as $year){
if($year === $this->startYear){
$currentMonth = intval($this->removeZeros($this->startMonth));
for($currentMonth; $currentMonth <= 12;$currentMonth++){
$this->queryArray[$year][] = (string)$this->addZeros($currentMonth);
$tempHowManyDays = cal_days_in_month(CAL_GREGORIAN, $this->addZeros($currentMonth), $year);
if($this->startYear === $this->addZeros($currentMonth)){
$currentDay = intval($this->removeZeros($this->startDay));
for($currentDay; $currentDay <= $tempHowManyDays; $currentDay){
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($currentDay)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($currentDay)]['Hours'] = 0;
}
} else {
for($i=1; $i<=$tempHowManyDays; $i++){
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($i)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($i)]['Hours'] = 0;
}
}
}
} elseif($year === $this->endYear) {
$endMonth = intval($this->removeZeros($this->endMonth));
for($a=1; $a <= $endMonth; $a++){
$this->queryArray[$year][] = (string)$this->addZeros($a);
if($a === $endMonth){
$tempHowManyDays = intval($this->removeZeros($this->endDay));
} else {
$tempHowManyDays = cal_days_in_month(CAL_GREGORIAN, $this->addZeros($a), $year);
}
for($b=1; $b<=$tempHowManyDays; $b++){
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['Hours'] = 0;
}
}
} else {
for($a=1; $a <= 12; $a++){
$this->queryArray[$year][] = (string)$this->addZeros($a);
$tempHowManyDays = cal_days_in_month(CAL_GREGORIAN, $this->addZeros($a), $year);
for($b=1; $b<=$tempHowManyDays; $b++){
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['Hours'] = 0;
}
}
}
}
var_dump($this->queryArray);
}
private function dateDifference(){
$now = strtotime($this->DateFrom);
$your_date = strtotime($this->DateTo);
$datediff = $your_date - $now;
$this->theDateDif = round($datediff / (60 * 60 * 24));
}
function __construct($pdo, $theArray, $generals = null){
if($generals !== null){ $this->generals = $generals; }
$this->pdo = $pdo;
if(isset($theArray['DateFrom']) && !empty($theArray['DateFrom'])){ $this->DateFrom = $theArray['DateFrom']; }
if(isset($theArray['DateTo']) && !empty($theArray['DateTo'])){ $this->DateTo = $theArray['DateTo']; }
$this->makeDates();
$this->dateDifference();
$this->chartItemVersion();
$this->makingQueryArray();
var_dump($this->queryArray);
}
}
$theArray = array();
$amhStatistics = new statisticsClass($pdo, $theArray, $generals);
I have been playing around with it for a while and can not get this array to function corectly.
The array should look like this:
array(){
'2018' => array(
01 => array(
01 => array(
'ticket' => 0,
'hours' => 0,
),
02 => array(
'ticket' => 0,
'hours' => 0,
)
)
)
}
As stated the only stipulation is that the start date should start at the start date and the end date should start at the end date.
Could someone point me in the right direction.
Cheers.
Your makingQueryArray function seems complicate - I believe you should solve it differently.
You can use dateperiod to get all days between 2 dates:
$startDate = '2010-10-01';
$endDate = '2010-10-05';
$period = new DatePeriod(new DateTime($startDate), new DateInterval('P1D'), new DateTime($endDate));
Now You can loop on all days and set you array:
foreach ($period as $key => $value) {
$d = explode("-", $value->format('Y-m-d'));
$res[$d[0]][$d[1]][$d[2]] = array('ticket' => 0, 'hours' => 0);
}
$res will give you your desire output. Live example: 3v4l

Counting the (year)quarters between two dates

I have project built using laravel and a I have to build a function that counts all the complete quarters that are in the selected date range - the dates used are inserted via input.
Here are the quarters(i used numerical representations for the months)
01 - 03 first quarter
04 - 06 second quarter
07 - 09 third quarter
10 - 12 forth quarter
I would really appreciate your help,because I've been at it for an entire day now and basically have nothing to show for it,i thing I've been trying so hard i'm actually at the point where i'm so tired, i can t think straight.
I do have some code but it;s worthless, because it doesn't work, and any kind of idea or snippet of code is welcomed.
Thanks for your help in advance.
I managed to do this using multiple functions; basically, if this is needed for chart statistics, then a more specific approach might be the case.
I have done this in Laravel with timestamp dates as input (this code can be adapted for getting semesters also :) , it works and is already tested):
public static function getQuartersBetween($start_ts, $end_ts)
{
$quarters = [];
$months_per_year = [];
$years = self::getYearsBetween($start_ts, $end_ts);
$months = self::getMonthsBetween($start_ts, $end_ts);
foreach ($years as $year) {
foreach ($months as $month) {
if ($year->format('Y') == $month->format('Y')) {
$months_per_year[$year->format('Y')][] = $month;
}
}
}
foreach ($months_per_year as $year => $months) {
$january = new Date('01-01-' . $year);
$march = new Date('01-03-' . $year);
$april = new Date('01-04-' . $year);
$june = new Date('01-06-' . $year);
$july = new Date('01-07-' . $year);
$september = new Date('01-09-' . $year);
$october = new Date('01-10-' . $year);
$december = new Date('01-12-' . $year);
if (in_array($january, $months) && in_array($march, $months)) {
$quarter_per_year['label'] = 'T1 / ' . $year;
$quarter_per_year['start_day'] = $january->startOfMonth();
$quarter_per_year['end_day'] = $march->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($april, $months) && in_array($june, $months)) {
$quarter_per_year['label'] = 'T2 / ' . $year;
$quarter_per_year['start_day'] = $april->startOfMonth();
$quarter_per_year['end_day'] = $june->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($july, $months) && in_array($september, $months)) {
$quarter_per_year['label'] = 'T3 / ' . $year;
$quarter_per_year['start_day'] = $july->startOfMonth();
$quarter_per_year['end_day'] = $september->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($october, $months) && in_array($december, $months)) {
$quarter_per_year['label'] = 'T4 / ' . $year;
$quarter_per_year['start_day'] = $october->startOfMonth();
$quarter_per_year['end_day'] = $december->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
}
return $quarters;
}
and getting the years between:
public static function getYearsBetween($start_ts, $end_ts, $full_period = false)
{
$return_data = [];
$current = mktime(0, 0, 0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
while ($current < $end_ts) {
$temp_date = $current;
$year = new Date($temp_date);
$return_data[] = $year;
$current = strtotime("+1 year", $current); // add a year
}
if ($full_period) {
$return_data[] = $end_ts;
}
return $return_data;
}
, also getting the months needed
public static function getMonthsBetween($start_ts, $end_ts, $full_period = false)
{
$return_data = $month_list = [];
$current = mktime(0, 0, 0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
while ($current <= $end_ts) {
$temp_date = $current;
$date = new Date($temp_date);
$month_list[] = $date;
$current = strtotime("+1 month", $current); // add a month
}
$start_date_last_month = new Date(array_first($month_list));
$start_date_last_month = $start_date_last_month->startOfMonth()->format('m-d');
$temp_end_date = new Date($start_ts);
$temp_end_date = $temp_end_date->format('m-d');
if ($start_date_last_month < $temp_end_date) {
array_shift($month_list);
}
$end_date_last_month = new Date(end($month_list));
$current_day_month = $end_date_last_month->endOfMonth()->format('m-d');
$temp_end_date = new Date($end_ts);
$end_day_of_month = $temp_end_date->format('m-d');
if ($end_day_of_month < $current_day_month) {
array_pop($month_list);
}
if (count($month_list) == 0) {
$month_list[] = $end_date_last_month->subMonth();
}
$return_data = $month_list;
if ($full_period) {
$return_data[] = $end_ts;
}
return $return_data;
}
You can do something like in this example:
$February = 2;
$October = 10;
$completedQuarters = ceil($October/3) - ceil($February/3); // = 3
What about the quarter in which the date range starts, should it also count? If it should only count if it begins in the first month of a quarter you can check for it like this:
$completedQuarters = ceil($October/3) - ceil($February/3) -1; // = 2
if($February-1%3 == 0) $completedQuarters += 1;
You´re description is not very clear, let me know if that´s what you had in mind.
Not sure if the following is what you are meaning but might be useful
$date_start='2015/03/12';
$date_end='2017/11/14';
$timezone=new DateTimeZone('Europe/London');
$start=new DateTime( $date_start, $timezone );
$end=new DateTime( $date_end, $timezone );
$difference = $end->diff( $start );
$months = ( ( $difference->format('%y') * 12 ) + $difference->format('%m') );
$quarters = intval( $months / 3 );
printf( 'Quarters between %s and %s is %d covering %d months', $start->format('l, jS F Y'), $end->format('l, jS F Y'), $quarters, $months );
/*
This will output
----------------
Quarters between Thursday, 12th March 2015 and Tuesday, 14th November 2017 is 10 covering 32 months
*/
Something like this in the function and you should be set.
use Carbon\Carbon;
$first = Carbon::parse('2012-1-1'); //first param
$second = Carbon::parse('2014-9-15'); //second param
$fY = $first->year; //2012
$fQ = $first->quarter; //1
$sY = $second->year; //2014
$sQ = $second->quarter; //3
$n = 0; //the number of quarters we have counted
$i = 0; //an iterator we will use to determine if we are in the first year
for ($y=$fY; $y < $sY; $y++, $i++) { //for each year less than the second year (if any)
$s = ($i > 0) ? 1 : $fQ; //determine the starting quarter
for ($q=$s; $q <= 4; $q++) { //for each quarter
$n++; //count it
}
}
if ($sY > $fY) { //if both dates are not in the same year
$n = $n + $sQ; //total is the number of quarters we've counted plus the second quarter value
} else {
for ($q=$fQ; $q <= $sQ; $q++) { //for each quarter between the first quarter and second
$n++; //count it
}
}
print $n; //the value to return (11)

Correct way to make a schedule

I've been debating whether to use Date functions or just whether there is a cleaner way to make an array of a given day's minutes at the moment my code reads like this;
function emptySchedule()
{
$emptySchedule = [];
for ($h = 0; $h < 24; ++$h) {
for ($m = 0; $m < 60; ++$m) {
$emptySchedule[str_pad($h, 2, '0', STR_PAD_LEFT).':'.str_pad($m, 2, '0', STR_PAD_LEFT)] = [];
}
}
return $emptySchedule;
}
But it just feels dirty, is there a better way to achieve the same result or maybe a better way to handle the minutes in the day with a date object or even better a globally accepted correct way? I'd prefer not to use a package, but if there is a good one I'm open to it.
EDIT; for some context, I will be putting arrays into each minute of the day.
EDIT2: for the purpose of what this will be used for there is no need for any input, my final function was;
public function emptySchedule()
{
$startDate = date_create("today"); //Any start date works
$endDate = date_create("tomorrow"); //Any end date works
$step = new \DateInterval("PT1M"); //1 minute, can change
$date = $startDate;
$times = [];
while ($date <= $endDate) {
$times[$date->format("H:i")] = [];
$date = $date->add($step);
}
return $times;
}
This is what I'd do:
$startDate = date_create("today"); //Any start date works
$endDate = date_create("tomorrow"); //Any end date works
$step = new DateInterval("PT1M"); //1 minute, can change
$date = $startDate;
$times = [];
while ($date <= $endDate) {
$times[$date->format("H:i")] = [];
$date = $date->add($step);
}
print_r($times);
http://sandbox.onlinephpfunctions.com/code/dd91a8f3f1707ca20aae93f70969275d5fb8dedd
Well, a more elegant approach of your code is:
<?php
function emptySchedule($hoursInit = date('G'), $hoursActive = 24)
{
$emptySchedule = [];
for ($h = $hoursInit; $h < $hoursActive; ++$h) {
for ($m = 0; $m < 60; ++$m) {
$emptySchedule[sprintf('%02d:%02d', $h, $m)] = [];
}
}
return $emptySchedule;
}
You can use interval too, working with lunch hours in your schedule and stuff:
<?php
function emptySchedule($hoursInit = date('G'), $hoursActive = 24, $interval = false)
{
$emptySchedule = [];
for ($h = $hoursInit; $h < $hoursActive; ++$h) {
if ($interval && ($h < $interval['start'] || $h > $interval['end'])) {
for ($m = 0; $m < 60; ++$m) {
$emptySchedule[sprintf('%02d:%02d', $h, $m)] = [];
}
}
}
return $emptySchedule;
}
But, like #deceze said, using date functions is a must, it's not simple to do right now, I'll try to figure out a better way;

Date range array excluding the Sunday & the holiday in PHP

I have a function which returns all the dates between two dates in an array, But I need to exclude Sundays in that array.
public function dateRange($first, $last, $step = '+1 day', $format = 'd/m/Y' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
After excluding the Sundays, I have a table where I will be storing some dates, I need to exclude those dates from the array too.
like, If I enter the date range as 01-05-2012(DD-MM-YYYY) to 10-05-2012,
The 06-05-2012 will be Sunday & the date 01-05-2012 & 08-05-2012 will be in the table which I mentioned above,
The final out put should be like,
02-05-2012
03-05-2012
04-05-2012
05-05-2012
07-05-2012
09-05-2012
10-05-2012
How to do this in PHP ?
I tried some but couldn't find the right way to do it.
For the Sundays part:
public function dateRange($first, $last, $step = '+1 day', $format = 'd/m/Y' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
if (date("D", $current) != "Sun")
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
For the holidays part:
First you need to load the dates into some kind of array and then loop through the array for each of your dates and check if they match.
I found the answer for my question, Thanks for the people who helped me.
public function dateRange($first, $last, $step = '+1 day', $format = 'd/m/Y' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$sql = "SELECT * FROM ost_holidays where holiday_date='".date('Y-m-d', $current)."' LIMIT 1";
$sql = db_query($sql);
$sql = db_fetch_array($sql);
if($sql['holiday_date'] != date('Y-m-d',$current))
if (date('w', $current) != 0)
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
The above code is for removing the holidays & the Sundays in the given range.
I did this same above method in Jquery
//Convert dates into desired formatt
function convertDates(str) {
var date = new Date(str),
mnth = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
return [date.getFullYear(), mnth, day].join("-");
}
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate, holidays) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
//Indise Some Function
var datesTemp = [];
var dates = getDates(new Date(prodDet.details.date1), new Date(prodDet.details.date2));
dates.forEach(function(date) {
if (date.getDay() != 0) {
datesTemp.push(convertDates(date));
}
});
datesTemp.forEach(function(date) {
for (var j = 0; j < prodDet.holidays.length; j++) {
if ((prodDet.holidays[j] != date)) {
ideal.idates.push(date);
}
}
});
console.log(ideal.idates);
//Function Ends Here

Categories