Filter Date by FinancialYear - c#

I have a table where i needed to filter the data by financial year.
Financial year is between April 1 of current year and March 31st of next year.For example:The current year is 2016 so the current financial year comes between April 1 2016 and March 31 2017.
The table
Id CenterId SlNo Date
1 1 5 2016-01-09 10:51:43.480
2 2 10 2016-01-09 10:51:43.480
I wanted to get the Slno where the CenterId=1 and Date will between current financial year.
My concern is Do i need another column of date for filtering financial year.
Any help is highly appreciated?

No you can do it without creating a new column. Simply calculate the current financial year dates like this:-
DateTime currentFinancialYearStartDate = new DateTime(DateTime.Today.Year, 4, 1);
DateTime currentFinancialYearEndDate = new DateTime(DateTime.Today.Year + 1, 3, 31);
Then, Simply use them in your filter like this:-
var result = dbContext.Sample.Where(x => x.CenterId == 1
&& x.Date >= currentFinancialYearStartDate
&& x.Date <= currentFinancialYearEndDate)
.Select(x => x.Slno);

Related

C# Get Month Name to compare it

I have a scenario, my database update table with one record every few minutes with a specific date. now I need to extract the month to check if month name equal to (April to October).
How to achieve that.
Please assist.
You can get the month name as below:
var dateTime = DateTime.Now;
int month = dateTime.Month;
if (month >= 4 && month <= 10)
{
// Month is between 4 & 10...
// Get the full month name: dateTime.ToString("MMMM")
}

Grabbing most recent transaction/record

I'm having trouble creating a linq statement that would grab the most recent transaction that happened before the startdate specified. Was wondering if anyone can help me.
For example startdate is January 20st.
Id LoanId TransactionDate InterestDate Balance
1 5 January 5 January 3 5000
1 5 January 30 January 5 10000
2 5 January 22 January 22 4000
3 6 January 3 January 1 2000
I should have a list below
Id LoanId TransactionDate InterestDate Balance
1 5 January 5 January 3 5000
3 6 January 3 January 1 2000
I'm having trouble grouping by and grabbing the correct values.
var transactions = ctx.Transactions.Where(x => x.Date <= startDate)
.GroupBy(x => x.LoanId)
.Select(x => new TransactionDTO
{
LoanId = ...
TransactionDate = ...
InterestDate = ....
Balance = ...
});
One way would be filtering by startDate, grouping by ID, ordering by date, and grabbing the first element of the group:
var res = tx
.Where(tx => tx.TransactionDate <= startDate)
.GroupBy(tx => tx.Id)
.Select(g => g.OrderBy(tx => tx.Date).First());

How to get the current month date wise records using linq to sql?

I want to get the count of rows by date for each day this month, like this:
Date count
1/03/2013 18
2/03/2013 41
28/03/2013 12
29/03/2013 14
How to write the query for that?
So, I assume you have some table with a datetime field in which you have the date "1/03/2013" 18 times, meaning you have 18 rows in that table with that date.
Then you should get the count of each day of a month in a year by something like this:
var year = 2013;
var month = 3;
var q = from t in DBContext.TableName
where t.DateField.Year == year && t.DateField.Month == month
group t by t.DateField.Date
into g
select new
{
dateField = g.Key,
countField = g.Count()
};
See also the LINQ to SQL Samples

Parse out monthly items from a collection of DateTime objects

I previously asked this question to take a oollection of datetime objects and group them by dayOfweek and time
So just to recap: I take a collection of DateTime
List<DateTime> collectionOfDateTime = GetDateColletion();
and then grouping by dayofWeek and time of day by doing this
var byDayOfWeek = collectionOfDateTime.GroupBy(dt => dt.DayOfWeek + "-" + dt.Hour + "-" + dt.Minute);
So at this point, I have these grouped by week (consistent time) working perfectly.
I now have a new requirement to group by Month instead of by week. When i say "month", its not the same day of the month but something like "the first tuesday of each Month"
I am trying to figure out what "key" to use in a group by to group all items that fit that monthly logic (the first tuesday of the month, the second friday of each month, etc)
As an example lets say i had these dates to start out with;
var date1 = new DateTime(2013, 1, 4).AddHours(8); // This is the first Friday in Jan
var date2 = new DateTime(2013, 2, 1).AddHours(8); // This is the first Friday in Feb
var date3 = new DateTime(2013, 1, 5).AddHours(3); // This is the first Sat in Jan
var date4 = new DateTime(2013, 2, 2).AddHours(3); // This is the first Sat in Feb
var date5 = new DateTime(2013, 2, 2).AddHours(6);  // This is the first Sat in Feb - different time
If these were the dates that went into the original array, i need a groupby to end up with 3 groups.
The first group would have date1 & date2 in it
The second group would have date3 and date4 in it.
date5 would be on its own as it doesn't match any of the other groups given the different time
Can anyone suggest anyway to group by that criteria?
I think it's easier than it looks:
var byDayOfMonth = from d in dates
let h = (d.Day / 7) + 1
group d by new { d.DayOfWeek, h } into g
select g;
Local variable h = (d.Day / 7) + 1 sets which DayOfWeek within that month it actually is.
I run it for test and received 2 groups, exactly the same as in your example. Keys for that groups are:
{ DayOfWeek = Friday, h = 1 }
{ DayOfWeek = Saturday, h = 1 }
What means, there are groups for 'First Friday of month' and 'First Saturday of month'.
You can easily extend grouping key by d.Hour and/or d.Minute if you like:
var byDayOfMonth = from d in dates
let h = (d.Day / 7) + 1
group d by new { d.DayOfWeek, h, d.Hour, d.Minute } into g
select g;
Results (keys only):
{ DayOfWeek = Friday, h = 1, Hour = 8, Minute = 0 }
{ DayOfWeek = Saturday, h = 1, Hour = 3, Minute = 0 }
{ DayOfWeek = Saturday, h = 1, Hour = 6, Minute = 0 }
There is probably an easier way to do this but this is what's come to me:
I gather from your question that you need to group everything from "the first Tuesday of February until the first Monday of March" etc. such that you get these "month" spans that are a variable number of days - depending on the month in which they start. If so then you really need to break this down into ranges using the day of the year so:
Group by the First Wednesday of the Month 2013
Group 0 (0-1)
All DayOfYear between 0 and 1 2013
Group 1 (2-36)
The first Wednesday of the month: January is DayOfYear 2.
The first Wednesday of the month: February is DayOfYear 37.
etc.
So the first range is a function f such that f(32) = 1 (DayOfYear is 32) because it falls in the range 2 to 37. This f is an indexed collection of ranges, finding the item in the collection that a given DayOfYear falls into, and returning that item's index as the group number.
You can dynamically build this table by getting your min and max dates from GetDateCollection to determine the overall range. Because the logic surrounding dates is a pretty complex topic in of itself I'd fall back on a library like NodaTime (specifically the arithmetic documentation), start with the min date, advance day by day until I found the first qualifying day (i.e., "first Monday of the month") and create a range 0 to that day - 1 as group 0 and push that onto an indexed collection (ArrayList likely). Then loop from that date using LocalDate.PlusWeeks(1) until the month changes, constructing a new range and pushing that range onto the same indexed collection.
Each time you cross into a new year you'll have to add 365 (or 366 if the previous year is a leap year) to your DayOfYear as you build your indexed collection since DayOfYear resets each year.
Now you've got a collection of ranges that acts as a table that groups days into the desired units based on their DayOfYear.
Write a function that traverses the table comparing the DayOfYear (+ [365|366] * x where x is the # of years the date you are comparing is from your min year) of a given date against the items in the collection until you locate the range that day falls within, and return that index of that item as the group number. (Alternatively each range could be a Func<DateTime,bool> that returns true if the provided DateTime falls in that range.)
An alternative data structure to the collection of ranges would be an array of ushort with length equal to all the days from min to max dates in your date range, and the value for each day their assigned group number (calculated with ranges, as above). This will perform faster for grouping, though the performance may not be noticeable if you're working with a smaller dataset (only a few hundred dates).
To group by using Linq maybe this code will help you:
List<DateTime> collectionOfDateTime = GetDateColletion();
collectionOfDateTime.GroupBy(s => Convert.ToInt16(s.DayOfWeek) & s.Hour & s.Minute);

Linq list for month+year for the whole year

Looking for linq query to fill a list with month + year for example (January 2012)
starting form current month
var currentdate = System.DateTime.Now
If Dec 2011 is the current month
then list should be like this
December 2011
January 2012
......
November 2012
var months =
Enumerable.Range(0, 12).
Select(n => DateTime.Today.AddMonths(n)).
Select(d = new { Year = d.Year, Month = d.Month });
I'm editing to turn my sample code into a method that I might almost use in production because it's more testable and culture-aware:
public IEnumerable GetMonths(DateTime currentDate, IFormatProvider provider)
{
return from i in Enumerable.Range(0, 12)
let now = currentDate.AddMonths(i)
select new
{
MonthLabel = now.ToString("MMMM", provider),
Month = now.Month,
Year = now.Year
};
}
This outputs (on a French computer):

Categories