-loop, is there easier way to do with carbon? - for-loop

I'm using Laravel 5.7 and carbon 1.x.
I need to build dateLooper which interval is 5 days and follows calender dates.
I need to find the way build looper which add 5 days for startdate.
ex.
$startDate = "2014-01-01";
$interval = "5";
so $endDate = $startDate + 5 ;
so endDates 2014-01-05
2014-01-10
till 2014-01-30, so this is tricky because need to follow calender.
Next 2014-02-04.
I was reading Carbon but did not find any examples
which could have open solution for my problem.
And I realized that L5.7 is still using 1.x carbon.
I have tried to build double for-loop, but did not work
as it stops after reach end of inside loop.
$month ="13" ; // +1;
$day ="29" ; // +1;
for ($i = 1; $i < $month; $i++)
{
echo "Month: ".$i.'<br/>';
for ($i = 1; $i < $day; $i++)
{
echo "Day: ".$i.'<br/>';
}
}
1) So is there way to do with Carbon?
or is there some other library which I could use? Ideas..
Thanks MikroMike.

I found it from How to add CarbonInterval instance in Carbon instance
$carbon = Carbon::now();
$monthLater = clone $carbon;
$monthLater->addDay(15);
dd($carbon, $monthLater);
This has resolved my issue.

Related

Getting non overlapping between two dates with Carbon

UseCase: Admin assigns tasks to People. Before we assign them we can see their tasks in a gantt chart. According to the task assign date and deadline, conflict days (overlap days) are generated between tasks.
I wrote this function to get overlapping dates between two dates. But now I need to get non overlapping days between two dates, below is the function I wrote.
$tasks = Assign_review_tasks::where('assigned_to', $employee)
->where('is_active', \Constants::$REVIEW_ACTIVE)
->whereNotNull('permit_id')->get();
$obj['task'] = count($tasks);
// count($tasks));
if (count($tasks) > 0) {
if (count($tasks) > 1) {
$start_one = $tasks[count($tasks) - 1]->start_date;
$end_one = $tasks[count($tasks) - 1]->end_date;
$end_two = $tasks[count($tasks) - 2]->end_date;
$start_two = $tasks[count($tasks) - 2]->start_date;
if ($start_one <= $end_two && $end_one >= $start_two) { //If the dates overlap
$obj['day'] = Carbon::parse(min($end_one, $end_two))->diff(Carbon::parse(max($start_two, $start_one)))->days + 1; //return how many days overlap
} else {
$obj['day'] = 0;
}
// $arr[] = $obj;
} else {
$obj['day'] = 0;
}
} else {
$obj['day'] = 0;
}
$arr[] = $obj;
start_date and end_date are taken from database,
I tried modifying it to,
(Carbon::parse((min($end_one, $end_two))->add(Carbon::parse(max($start_two, $start_one))))->days)->diff(Carbon::parse(min($end_one, $end_two))->diff(Carbon::parse(max($start_two, $start_one)))->days + 1);
But it didn't work, in simple terms this is what I want,
Non conflicting days = (end1-start1 + end2-start2)- Current overlapping days
I'm having trouble translate this expression . Could you help me? Thanks in advance
before trying to reimplement complex stuff I recommend you take a look at enhanced-period for Carbon
composer require cmixin/enhanced-period
CarbonPeriod::diff macro method is what I think you're looking for:
use Carbon\CarbonPeriod;
use Cmixin\EnhancedPeriod;
CarbonPeriod::mixin(EnhancedPeriod::class);
$a = CarbonPeriod::create('2018-01-01', '2018-01-31');
$b = CarbonPeriod::create('2018-02-10', '2018-02-20');
$c = CarbonPeriod::create('2018-02-11', '2018-03-31');
$current = CarbonPeriod::create('2018-01-20', '2018-03-15');
foreach ($current->diff($a, $b, $c) as $period) {
foreach ($period as $day) {
echo $day . "\n";
}
}
This will output all the days that are in $current but not in any of the other periods. (E.g. non-conflicting days)

How to compare carbon date in laravel?

I try to check if today is the 3 days after the registration day or not, so i compare today date with the registration date plus 3 days. But i think my code is not working, this is my code:
$get_tanggal_permohonan = DB::table('data_pemohon')->select('tanggal_permohonan')->where('noper', $noper)->first();
$tanggal_permohonan = $get_tanggal_permohonan->tanggal_permohonan;
$Dday = \Carbon\Carbon::parse($tanggal_permohonan);
$today = \Carbon\Carbon::now()->toDateString();
$today = \Carbon\Carbon::parse($date);
if($today < $Dday->subDays(3)){
echo "not the time to come";
}else{
echo "time to come"
}
I have no idea to solve this error, help me please. Thank you.
You can use DiffInDays()
if( $Dday->diffInDays($today) > 3){
echo "not the time to come";
}else{
echo "time to come"
}
You can use the isSameDay() method and the Laravel today() helper function:
$get_tanggal_permohonan = DB::table('data_pemohon')->select('tanggal_permohonan')->where('noper', $noper)->first();
$tanggal_permohonan = $get_tanggal_permohonan->tanggal_permohonan;
$Dday = \Carbon\Carbon::parse($tanggal_permohonan);
if ($Dday->addDays(3)->isSameDay(today())) {
echo "not the time to come";
} else {
echo "time to come";
}
Question already anwsered here How to compare two Carbon Timestamps?
if (Carbon::parse($date)->gt(Carbon::now()))
for more http://carbon.nesbot.com/docs/#api-comparison

Laravel - Get data based on date range using eloquent

Heei, I want to show data according to daterange. Specifically data on this day and 6 days to go. Here's my code now.
Controller
$hari = [];
for ($i=0; $i < 6; $i++)
{
$hari[] = date("Y M d") + $i;
}
$booking_room = jadwal_meeting::whereBetween('tanggal', [$hari, $hari + 6])->get();
return view('homepage')->with($booking_room);
Note: 'tanggal' is a field on table.
But I just get error like this
Unsupported operand types
: $booking_room = jadwal_meeting::whereBetween('tanggal', [$hari, $hari + 6])->get();
What's wrong with my code, anyone can help me please :)
Since $hari is an array, you have to use something like this:
$booking_room = jadwal_meeting::whereBetween('tanggal', [$hari[0], $hari[5]])->get();
Or more general:
$booking_room = jadwal_meeting::whereBetween('tanggal', [$hari[0], end($hari)])->get();
Try this code it will help you.
$from = '2018-04-12';
$to = date('Y-m-d', strtotime($from. ' + 6 days'));
$reservations = Reservation::whereBetween('tanggal', [$from, $to])
->get();
Thanks,

Insert $i variable in object call in Propel & PHP

I'm currently busy rebuilding our CMS in Propel. I currently have the functions to get several body's from our database but i'm struggling to get a desired one based on a $i variable.
The function is as follows:
for ($i = 0; $i < $item->getColumns(); $i++) {
if (strlen(strip_tags(stripslashes($item->getBody1()))) > 100) {
$body = strip_tags(stripslashes(substr(strip_tags($item->getBody$i()), 0, strpos(strip_tags($item->getBody.$i()), ' ', 100)))) . ' ...';
} else {
$body = stripslashes($item->getBody.$i());
}
}
In the function above you the see code $item->getBody1(). I want the function to use the $i variable to get the desired body, so for example if $i = 2, the getBody function should be $item->getBody2().
I've tried to use $item->getBody.$i() but that doesn't work. Is there a way I could create this?
Any help is appreciated!
This is not an issue with Propel, but with PHP.
Instead of using:
$item->getBody$i();
Use:
$getIthBodyMethod = 'getBody' . $i;
$item->$getIthBodyMethod();
PHP manual on variable methods

How to iterate through range of Dates?

In my script, I need to iterate through a range of dates given the start date and end date. How can I do this in Perl?
Use DateTime module. Here is a simple example which lists the ten previous days:
use 5.012;
use warnings;
use DateTime;
my $end = DateTime->now;
my $day = $end->clone->subtract( days => 10 ); # ten days ago
while ($day < $end) {
say $day;
$day->add( days => 1 ); # move along to next day
}
Update (after seeing your comment/update):
To parse in a date string then look at the DateTime::Format on modules CPAN.
Here is an example using DateTime::Format::DateParse which does parse YYYY/MM/DD:
use DateTime::Format::DateParse;
my $d = DateTime::Format::DateParse->parse_datetime( '2010/06/23' );
One easy approach is to use the Date::Simple module, which makes use of operator-overloading:
use strict;
use warnings;
use Date::Simple;
my $date = Date::Simple->new ( '2010-01-01' ); # Stores Date::Simple object
my $endDate = Date::Simple->today; # Today's date
while ( ++$date < $endDate ) {
print ( $date - $endDate ) , "day",
( ( $date-$endDate) == 1 ? '' : 's' ), " ago\n";
}
use DateTime::Format::Strptime qw();
my $start = DateTime::Format::Strptime->new(pattern => '%Y/%m/%d')->parse_datetime('2010/08/16');
my $end = DateTime::Format::Strptime->new(pattern => '%Y/%m/%d')->parse_datetime('2010/11/24');
while ($start < $end) {
$start->add(days => 1);
say $start->ymd('/');
}
I like to use the fact that strftime will normalize the date for me:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw/strftime/;
my $start = "2010/08/16";
my $end = "2010/09/16";
my #time = (0, 0, 0);
my ($y, $m, $d) = split "/", $start;
$y -= 1900;
$m--;
my $offset = 0;
while ((my $date = strftime "%Y/%m/%d", #time, $d + $offset, $m, $y) le $end) {
print "$date\n";
} continue {
$offset++;
}
You can try Date::Calc::Iterator
# This puts all the dates from Dec 1, 2003 to Dec 10, 2003 in #dates1
# #dates1 will contain ([2003,12,1],[2003,12,2] ... [2003,12,10]) ;
my $i1 = Date::Calc::Iterator->new(from => [2003,12,1], to => [2003,12,10]) ;
my #dates1 ;
push #dates1,$_ while $_ = $i1->next ;
If installing extra perl modules is not preferable, one can use this approach, based on a core perl library POSIX:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(strftime);
# CREATE CALENDAR
my #Calendar = ();
my $years = 3;
my #Now = localtime(); # An array of 9 date-time parameters.
for my $count ( 0 .. ( 365 * $years ) ) {
# If date is January 1st, manual shift to December 31st is needed,
# because days ([yday][2]) are counted from January 31st and never shift back one year.
if( $Now[4] == 0 && $Now[3] == 1 ) {
unshift #Calendar, strftime( "%Y-%m-%d", #Now );
$Now[5] --; # Reduce by one the sixth array element #5 - year.
$Now[4] = 11; # Set fifth array element № 4 - to December.
$Now[3] = 31; # Set fourth array element № 3 - to 31st.
} else {
unshift #Calendar, strftime( "%Y-%m-%d", #Now );
$Now[3] --;
}
}
# Print out.
my $size = #Calendar;
for (my $i = 0; $i < $size; $i++) {
print $Calendar[$i]."\n";
}
Perl has a rich array of time and date manipulation modules, as seen here:
http://datetime.perl.org/?Modules
And there are some examples of date and time problems there as well.
With Perl, there's always more than one way to do it.

Resources