a user chose date and I get that date and make 3 more dates as below
$start_date = Carbon::parse($request->start_date);
$m1 = $start_date->addMonths(1);
$m3 = $start_date->addMonths(3);
$m6 = $start_date->addMonths(6);
then I get the database values which I need to compare the dates with as below
$model = Model::WhereDate('start_date','>',$request->start_date)->get();
and I loop through them
$duration = 0;
foreach ($model as $value) {
if (Carbon::parse($value->start_date)->between($start_date, $m3) || Carbon::parse($value->end_date)->between($start_date, $m3)) {
$duration = 1;
}
if (Carbon::parse($value->start_date)->between($start_date, $m3) || Carbon::parse($value->end_date)->between($start_date, $m3)) {
$duration = 3;
}
if (Carbon::parse($value->start_date)->between($start_date, $m6) || Carbon::parse($value->end_date)->between($start_date, $m6)) {
$duration = 6;
}
}
is there a better way to do this? I'm not OK with comparing like this Carbon::parse($value->start_date)->between($start_date, $m6) || Carbon::parse($value->end_date)->between($start_date, $m6)
PS - this not to get the duration between dates but to compare them in given date range whether it's in that range.the twist is that comparing date is also a range dates.
I apologies for my language if there is any unclear part; let me know I'll explain it
Related
i want to sum profit by activating multiple plans. I am using get() with foreach but it returns only last row data. not all rows data. its strange while on other queries it returns all rows data.
for example, I have 2 deposits one 25$ and 2nd 35$ its returns 35$ data only.
i tried with
$deposits = Deposit::get();
but it is not working I went to increase rows to 12 but still, it returns data of 12th row only
$deposits = Deposit::where('account_id', $account->id)->where('status',1)->get();
foreach($deposits as $pn) {
$plans = package::where('id',$pn->plan)->first();
$percent = $plans->min_amount * $plans->percent/100;
}
After discussing in chat, the real problem is adding up the percentages during looping :
$percent = 0;
foreach ($deposited as $de) {
$pack = Package::Where('id', $de->plan)->first();
$log = Deposit::Where('id', $de->id)->first();
$percent = $percent + ($log->amount * $pack->percent / 100);
}
I've an array of day name like ['Wednesday','Sunday','Monday']
now I want to find the next available dates That matched with the array from today's date. I want date. I tried for so long but none of them were successful. My code is given below
$datesAvailable = array();
$count = 0;
$dateToday = Carbon::now()->toDateTimeString();
//$avlDays is the array of day names
$avlDays = DB::table('doctor_schedules')
->select('available_days')
->where('department',$receivedDepartment)
->Where('doctor_id', $receivedDoctor)
->get();
for($k=5; $k > 0; $k++)
{
$dateToday = $dateToday->endOfWeek();
// $parsedDate = Carbon::parse($dateToday);
$dateTodayFormated = new Carbon($dateToday);
$nextDayName = $dateTodayFormated->englishDayOfWeek;
for($i = 0; $i <= 2; $i++)
{
if($avlDays === $nextDayName)
{
$datesAvailable[$count] = $nextDayName;
$count++;
}
}
}
return (['availableDates' => $dateToday]);
Solved
For the current date use
now()
https://laravel.com/docs/6.x/helpers#method-now
Carbon does this.
foreach ($avlDays as $day) {
$nextDay = Carbon::parse("next $day");
// do something with $nextDay...
}
So, assuming $avlDays is returning you a Carbon date range:
$avlDays = DB::table('doctor_schedules')
->select('available_days')
->where('department',$receivedDepartment)
->Where('doctor_id', $receivedDoctor)
->get()
->toArray();
The code below assumes that the array value from ['monday', 'tuesday' ...] is saved as $weekday.
If you are trying to find a specific date within a range that falls on a certain weekday, you can do something like:
$availableAppointments = [];
foreach ($avlDays as $day) {
if ($day->isDayOfWeek($weekday)) {
$availableAppointments[] = $day;
}
Then you can use $availableAppointments to list out the available dates on that day of the week.
I am trying to count the number of days between two dates the carbon::now and $start_date and when the status == complete the counting of days stops then get the total number of days.
if ($this->status === 'COMPLETED') {
$now = Carbon::now();
$start_date = Carbon::createFromFormat('Y-m-d', $this->start_date);
$this->start_date_to_current_date = $start_date->diffInDays($now, true);
}
But the problem is, the days still continues to count even the status is completed like for example the total days is 3 then in the next day it becomes 4 then ive tried doing this:
if ($this->status == null && $this->status === 'COMPLETED') {
$now = Carbon::now();
$start_date = Carbon::createFromFormat('Y-m-d', $this->start_date);
$this->start_date_to_current_date = $start_date->diffInDays($now, true);
}
But the value becomes zero. why is that ? :/
You need to log the complete date somewhere, and use it instead of now().
For instance:
if ($this->status === 'COMPLETED') {
$start_date = Carbon::createFromFormat('Y-m-d', $this->start_date);
$start_date->diffInDays($this->completed_date); // completed_date should come from db.
}
The problem here is that you're using the current date as complete date which is obviously changing everyday, hence you get different result each day.
let it only do that when you not yet, and do not repeat do it.
`if ($this->status == null && $this->status !== 'COMPLETED') {`
`$now = Carbon::now();`
`$start_date = Carbon::createFromFormat('Y-m-d', $this->start_date);`
`$this->start_date_to_current_date = $start_date->diffInDays($now, true);`
}
I would like to make an auto increment with a date + a number. Example: 16022017-1. However I can not add the date + the dash + the number.
1- I retrieve the latest invoices in the database
$exist = Contrats::where('number','like','%'.$dateNow->format('dmY').'%')->orderBy('number', 'desc')->get();
2- Here my condition adds value after the date however I can not add the "-" and the number.
if (count($exist) == 0){
$date = new \DateTime(null);
$contrat->number = $date->format('dmY');
} elseif (count($exist) == 1){
$date = new \DateTime(null);
$contrat->number = $date->format('dmY'), '-', 1;
} else {
echo "pb";
}
Do you have an idea how I can increment my date, dash and number? Thank you for your answers.
Quick shoot from the hip answer as i am munching on my salad... Seems that your suffix (number after the date) is the actual count since you seem to be skipping the first instance (0). Eloquent returns a collection... use the ->count() ...
if ($exist->count() > 0){
$date = new \DateTime(null);
$contrat->number = $date->format('dmY') . '-' . $exists->count();
} else {
$date = new \DateTime(null);
$contrat->number = $date->format('dmY');
}
Thanks already to Serge insas for his insight both here and here, which have been a godsend for me already. But...I'm having trouble tying everything together with date validation.
To clarify, I have a GAS intended to verify that the date in Column A is (a) more than seven days old and (b) not null. If both pass, the script determines the first empty row in Column G, and then pauses before completing various functions. The beginning of the script looks like...
function getStats() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName("Main");
var TITLE_ROW = 1;
var DATE_COL = 1;
var URL_COL = 4;
var sevendaysBefore = new Date(new Date().getTime()-7*24*60*60*1000);
if (DATE_COL != ''||(DATE_COL != null || DATE_COL< sevendaysBefore)) {
var end = sheet.getLastRow();
for( var i = 1; i < end; i++) {
var Gvals = sheet.getRange("G1:G").getValues();
var Glast = Gvals.filter(String).length;
var rowNum = TITLE_ROW+Glast;
var itemurl = sheet.getRange(rowNum,URL_COL).getValues();
Utilities.sleep(500);
...
I've clearly implemented something wrong, though, because the date validation doesn't workâthe script appears to function as though the data in Column A doesn't matter. I'm sure I've done something incredibly idiotic, but I'm too ignorant to spot it on my own. So...anyone know what I've overlooked?
While the other answer is probably working (didn't test), its approach is very different from yours.
Below is code that follows the same logic as yours but works at the array level (to follow recommendations in Best practices).
I added a few comments to show the differences, hoping it will help you to understand how it works.
function getStats() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName("Main");
var Glast; // define the variable for later use
var vals = sheet.getDataRange().getValues();// get all data in an array (do that before loop)
var TITLE_ROW = 0;// use array index instead of real row numbers
var DATE_COL = 0;// use array index instead of real column numbers
var URL_COL = 3;// use array index instead of real column numbers
var sevendaysBefore = new Date(new Date().getTime()-7*24*60*60*1000).getTime();// get native value in milliseconds to make comparison easier below
for( var i = 1; i < vals.length; i++) { // start loop from Row 2 (=array index 1)
if(vals[i][0]!='' && vals[i][0]!=null&&vals[i][0].getTime()<sevendaysBefore){continue};// use && instead of ||, we want ALL conditions to be true ( see !='' and !=null)
Glast = i; break ;// first occurrence of data meeting above condition (non null and date < 7 days before)
}
var itemurl = vals[Glast][URL_COL];// get the value from the array
Utilities.sleep(500);
//...
Mistake : You are hard coding DATE_COL = 1 and you are using this in if statement. It doesn't get the value of the cell. Also I am not getting your statement "date in Column A is (a) more than seven days old". Is that date is from a cell or you are iterating through all the cells in column A ?.
Below code will satisfy your need and I tested. Here as example I am checking date validation for cell R1C1(A1).
1)Get the date from cell. You can change it or Iterate the cells in column for date.
2) We have date.valueOf() method which returns the number of milliseconds since midnight 1970-01-01.
3) Validation : check the cell data is date and greater than 7 days
function compDate()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = sheet.getRange("A1"); //point1
var date01 = new Date();
var date02 = cell.getValue(); //point2
var dateDiff = (date01.valueOf()-date02.valueOf())/(24*60*60*1000);
if((isValidDate(date02)) == true && dateDiff > 7) //point3
Logger.log("success");
}
//below function will return true if the arg is valid date and false if not.
function isValidDate(d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
}