php DateTime diff return zero - oop

I am just wondering why DateTime::diff returns ZERO. i am expected to return 5 days, definitely i am doing something wrong. somebody here would please correct my code..
$oneYearPlus = str_replace(':', '-', date('Y:m:d', strtotime('+1 year', strtotime('now'))));
var_dump($oneYearPlus);
$date = new DateTime($oneYearPlus); ## 2015-09-26
var_dump($date); // Output
--------------------------------
object(DateTime)[18]
public 'date' => string '2015-09-27 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Moscow' (length=13)
--------------------------------
$warning = $date->sub(new DateInterval('P5D')); ## 2014-09-21
var_dump($warning); // Output
--------------------------------
object(DateTime)[18]
public 'date' => string '2015-09-22 00:00:00' (length=19)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/Moscow' (length=13)
--------------------------------
$interval = $warning->diff($date);
var_dump($interval->format('%a days')); ## output 0 days

$date gets subtracted value (the same value is returned) So $warning & $date has the same value -
to solve this problem... i just clone the $date variable ;-) and it works
$oneYearPlus = str_replace(':', '-', date('Y:m:d', strtotime('+1 year', strtotime('now'))));
var_dump($oneYearPlus);
$date = new DateTime($oneYearPlus); ## 2015-09-26
var_dump($date);
$clone = clone $date;
$warning = $date->sub(new DateInterval('P5D')); ## 2014-09-21
var_dump($warning);
$interval = $warning->diff($clone);
var_dump($interval->format('%a days')); ## output 0 days

Related

Total Leave Taken - How to update total leave taken in a leave_balances table for a specific user

I created a method called getSumOfLeaveTaken() in a Leave Models in order to sum the number of days taken for a leave for a specific user shown in a Leave Model below and call this methods in my controller to save the sum of leave taken in a leave_balances table. My leave_balance table is meant to save the sum of leave taken per leave_category and specific user. When I apply for a leave for 2 days the 2 days leaves was saved in leave_balance table and then later on I apply for another 3 days leave and the total_leave_taken is updated and summed up to 5 total_leave_taken
If another user apply for 2 days leave the total_leave_taken for that user is 7 days.
I stuck on how to make this correct as 2 days leaves becomes 7 days total leave taken. Please can anyone help
<?php
namespace App\Models;
use App\Models\Leave;
use DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Leave extends Model
{
use HasFactory;
protected $table = 'leaves';
protected $fillable = [
'created_by',
'leave_category_id',
'start_date',
'end_date',
'num_days',
'reason',
'publication_status',
'deletion_status',
];
public static function getSumOfLeaveTaken(){
$leavebalance = Leave::where('leave_category_id',1)->where('created_by',$userId = Auth::user()->id)->first()->sum('num_days');
return $leavebalance;
}
}
My store methode
public function store(Request $request) {
$sdates = date("D", strtotime($request->start_date));
$edates = date("D", strtotime($request->end_date));
$leave_application = $this->validate($request, [
'leave_category_id' => 'required',
'start_date' => 'required',
'end_date' => 'required',
]);
$start_date = Carbon::parse(request('start_date'));
$end_date = Carbon::parse(request('end_date'));
$days = $start_date->diffInWeekdays($end_date);
$weekly_holidays = WorkingDay::where('working_status', 0)
->get(['day'])
->toArray();
if($weekly_holidays != null){
foreach ($weekly_holidays as $weekly_holiday) {
if ($sdates == $weekly_holiday['day'] || $edates == $weekly_holiday['day']) {
return redirect()->route('leave.index')->with('exception', 'You select a holiday !');
}
}
}
$monthly_holidays = Holiday::where('holiday_date', '=', $request->start_date)
->first(['holiday_date']);
if($monthly_holidays == null){
$result = Leave::create($leave_application +['num_days' => $days] +['reason' =>request('reason')] + ['created_by' => auth()->user()->id]);
$rds = LeaveBalance::where('leave_category_id',$request->leave_category_id)->where('created_by',$userId = Auth::user()->id)->first();
if(!isset($rds)){
$carbon = Carbon::now();
$nowInTarawa = Carbon::now('Pacific/Tarawa');
$year = $nowInTarawa->format('Y');
$yearIntvalue = intval($year);
$leave_balance = new LeaveBalance();
$leave_balance->leave_category_id = $request->leave_category_id;
$leave_balance->created_by = $userId = Auth::user()->id;
$leave_balance->year = $yearIntvalue;
$leave_balance->total_leave_taken = $leaves = Leave::getSumOfLeaveTaken($request->leave_category_id);
$leave_balance->save();
}else
{
$leaves = Leave::getSumOfLeaveTaken($request->leave_category_id);
LeaveBalance::where('created_by', $userId)->where('leave_category_id',$request->leave_category_id)
->update(['total_leave_taken' => $leaves]);
}
$inserted_id = $result->id;
if (!empty($inserted_id)) {
return redirect()->route('leave.index')->with('message', 'Add successfully.');
}
return redirect()->route('leave.index')->with('exception', 'Operation failed !');
}
if($monthly_holidays != null){
return redirect()->route('leave.index')->with('exception', 'You select a holiday !');
}
}
Solved:
The link that help me solving this is found here Laravel - sum of current user
I just change my getSumOfLeaveTaken() logic to and able to sum leave taken for a specific user.
public static function getNumOfLeaveTaken($leave_category_id){
$leavebalance = DB::table('leaves')
->where('created_by', \Auth::user()->id)
->where('leave_category_id', $leave_category_id)
->sum('num_days');
return $leavebalance;
}

ASP.NET Core - Operator '==' cannot be applied to operands of type 'DateTime?' and 'int'

In ASP.NET Core-5 Web API I have this code:
public class DashboardCountDto
{
public int? AllMandateCount { get; set; }
public int? CurrentYearMandateCount { get; set; }
}
public List<DashboardCountDto> GetDashboardFieldCount()
{
DashboardCountDto data = new DashboardCountDto();
DateTime current = DateTime.Now;
data.CurrentYearMandateCount = _context.zib_mandates.Where(m => m.CreatedDate == current.Year).Select(c => c.Id).Distinct().Count();
List<DashboardCountDto> dataCount = new List<DashboardCountDto>();
dataCount.Add(data);
return dataCount;
}
CreatedDate is DateTime datatype
This is to return the count of records for the current year.
I got this error:
Operator '==' cannot be applied to operands of type 'DateTime?' and 'int'
How do I get this corrected?
Thanks
In your line you write
data.CurrentYearMandateCount = _context.zib_mandates.Where(m => m.CreatedDate == current.Year).Select(c => c.Id).Distinct().Count();
But CreatedDate is Date Type and current.Year is int type. so If you compare with year you should write
data.CurrentYearMandateCount = _context.zib_mandates.Where(m => m.CreatedDate.Year == current.Year).Select(c => c.Id).Distinct().Count();
Hopefully it works
try it:
public List<DashboardCountDto> GetDashboardFieldCount()
{
DashboardCountDto data = new DashboardCountDto();
DateTime current = DateTime.Now;
DateTime currentYear= DateTime.Parse($"{current.Year}/01/01");
data.CurrentYearMandateCount = _context.zib_mandates.Where(m => m.CreatedDate >= currentYear).Select(c => c.Id).Distinct().Count();
List<DashboardCountDto> dataCount = new List<DashboardCountDto>();
dataCount.Add(data);
return dataCount;
}

How to select all the days of the week from a given day?

Given a date I want to get all the other days of that same week, where in the week starts and ends on Saturday and Friday.
Model
public TimeModel
{
public int ID
public DateTime Day
}
What I'm currently doing
public Contrller{
private db = new ModelContext();
public AddDates(DateTime Date)
{
List<Model> list = new List<Model>();
int n = 0;
while(Date.DayofWeek != DayofWeek.Sauturday)
Date = Date.AddDats(-1) // keep subracting the date until I reach Saturday
while(Date.DayofWeek != DayofWeek.Friday
{
list.Add(Find(Date));
//Simply put for each date not Friday
// I find the corresponding model (the one with the same date)
//and add it to the list
Date = Date.AddDays(1)
}
list.Add(Find(Date)); // To add the Friday date to list
}
Note: Not exactly my code, just a simplification of my problem.
To summarize my solution:
a) Subtract given date until Saturday
b) Find model which corresponds to Date
c) Repeat until I reach Friday
d) Add to list once more to include Friday
Is it possible to create a linq/sql statement to simpyly select the needed models (with regards to Date)?
You can find a sample implementation that gets the current week.
List<TimeModel> list = new List<TimeModel>();
int n = 0;
for (int i = 0; i < 200; i++)
list.Add(new TimeModel{ID = i, Day = DateTime.Now.AddDays(-i)});
var currentDay = new TimeModel() {ID = 0, Day = DateTime.Now};
var previousSaturday = currentDay.Day.AddDays(-(int)currentDay.Day.DayOfWeek - 1);
var nextFriday = previousSaturday.AddDays(6);
var currentWeek = list.Where(p => p.Day.DayOfYear >= previousSaturday.DayOfYear && p.Day.DayOfYear <= nextFriday.DayOfYear).OrderBy(p => p.Day.DayOfYear).ToList();

Using SQL Server Date datatype and C# DateTime to select records

I have an ActionResult where I want to select records based on a date column in SQL Server. This date is in a column of type Date. I can't directly compare the dates since C# DateTime includes the time component and the Date datatype does not. Is there a nice way to do this?
public ActionResult AbsencesByDate(DateTime date)
{
var absences = from attendance in db.Attendances
where attendance.Date == date
select new
{
returnedPersonID = attendance.PersonID,
FullName = attendance.Person.FName + " " + attendance.Person.LName,
};
return Json(absences, JsonRequestBehavior.AllowGet);
}
You could remove the time part from your date parameter in your function.
Something like this :
public ActionResult AbsencesByDate(DateTime date)
{
date = date.Date;
var absences = from attendance in db.Attendances
where attendance.Date == date
select new
{
returnedPersonID = attendance.PersonID,
FullName = attendance.Person.FName + " " + attendance.Person.LName,
};
return Json(absences, JsonRequestBehavior.AllowGet);
}
try using:
where attendance.Date == date.Date

Advanced LINQ/ Lambda Expression

I have this model:
Public Class Tbl_Exercise
<Key()> Public Property Exercise_ID() As Integer
Public Property Exercise_Employee_ID() As Integer
Public Property Exercise_Create_Date() As Date
<ForeignKey("Tbl_Exercise_Type")> _
Public Property Exercise_Type_ID() As Integer
Public Property Exercise_Duration() As Integer
Public Overridable Property Tbl_Exercise_Type As Tbl_Exercise_Type
End Class
I need to get the sum of the Exercise_Duration for each week of the year. I need to then check if the sum for the week is greater than or equal to 150. If it is, I need to +1 another variable (a count). The goal is to display this:
# of weeks you've reached 150: X out of Z
(Where X is the count of weeks greater than or equal to 150 and Z is equal to the total number of weeks in the current year.)
Final
' get number of weeks the exercise goal was reached (greater than or equal to the goal)
Dim exerciseDb = New ExerciseDbContext
Dim exercise = exerciseDb.Tbl_Exercises.Where(Function(x) x.Exercise_Employee_ID = empId)
Dim weeks = exercise.ToList.GroupBy(Function(x) CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(x.Exercise_Create_Date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday))
Dim totalWeeks = 0
For Each week In weeks
Dim sum = week.Sum(Function(x) x.Exercise_Duration)
If sum > 150 Then
totalWeeks += 1
End If
Next
Debug.Print("over150: " + totalWeeks.ToString)
using System.Globalization;
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;
var recap =
(from e in exercises
group e by cal.GetWeekOfYear(e.Exercise_Create_Date,
dfi.CalendarWeekRule,
dfi.FirstDayOfWeek)
into g
select new
{
g.Key,
Total = g.Sum(x => x.Exercise_Duration)
}
into p
where p.Total > 150
select p)
.Count();
Here is an example in C#:
public class Exercise
{
public DateTime CreateDate { get; set; }
public int Duration { get; set; }
}
class Program
{
static void Main()
{
Exercise[] ex = new Exercise[]
{
new Exercise { CreateDate = DateTime.Parse("1/1/2012"), Duration = 160 },
new Exercise { CreateDate = DateTime.Parse("1/8/2012"), Duration = 160 },
new Exercise { CreateDate = DateTime.Parse("1/15/2012"), Duration = 160 },
new Exercise { CreateDate = DateTime.Parse("2/1/2012"), Duration = 100 },
new Exercise { CreateDate = DateTime.Parse("3/1/2012"), Duration = 75 },
new Exercise { CreateDate = DateTime.Parse("3/1/2012"), Duration = 80 }
};
var weeks = ex.GroupBy(x => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(x.CreateDate, CalendarWeekRule.FirstDay, DayOfWeek.Sunday));
int currentweek = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
int over150 = weeks.Where(group => group.Sum(item => item.Duration) > 150).Count();
Console.WriteLine(String.Format("# of weeks you've reached 150: {0} out of {1}", over150, currentweek));
}
}