Number of days for a given year inside a date range - c#

Say I have an year, 2017.
I then have a date range, 01/07/2017 - 01-07-2018 OR 01/07/2017 - 01-01-2017 OR 01/01/2016 - 01/01/2018 ( <- this should return 365 days)
I now need to calculate how many total days are there in the given range for the given year.
Note that dates are stored as dd/mm/yyyy with an always 00:00:00 time.
What would the best logic be considering all possible cases of ranges?

You can compute the start and end dates for a year easily:
var start2017 = new DateTime(2017,1,1);
var end2017 = new DateTime(2017,12,31);
And then you can compute the overlap between this new range and your other range1:
var startOverlap = start2017 < startOtherRange ? startOtherRange : start2017;
var endOverlap = end2017 > endOtherRange ? endOtherRange : end2017;
var totalDays = (endOverlap - startOverlap).TotalDays + 1;
The above is correct if ranges are meant to include both their start and end dates. If you want, say, an exclusive endpoint then we'd adjust the end of out 2017 computed range one day further forwards and would no longer require the +1 adjustment at the end)
(And I presume you can derive from there how to turn it into a function if required that takes year, startRange, endRange parameters and does the above with some appropriate renaming)
1I had some vague recollection of DateTime.Min(value1, value2) and similarly for Max but it's definitely not in the BCL that I can see. Those would replace the conditional operators on the following lines. Once C# has "extension everything" these functions could be written as static extensions to DateTime.

Related

Sum times over 24:00 in C#

I want to collect a few hours, but if sum is over 24:00 I take as like it: 1.01:20
How can it in c#:
23:00 + 02:00 = 25:00 ?
Best regards
What has this question to do with Mysql at all? You are asking about the sum of multiple C# TimeSpan, aren't you? Then TotalHours might give you the answer:
TimeSpan ts = TimeSpan.FromHours(23);
ts = ts + TimeSpan.FromHours(2);
int hours = (int) ts.TotalHours;
If you want the sum as formatted string "25:00", use this approach:
string hourMinute = $"{((int)ts.TotalHours).ToString("D2")}:{ts.Minutes.ToString("D2")}";
The ToString("D2") ensures that you always have at least two digits for the hours and minutes, with a leading zero if necessary. Read: Standard numeric format strings

multiple date range and check if it is sequential. c# MVC

We have this project and one of the business requirement is it allows the client to input a multiple date range and check the individual dates if it is sequential/continuous or not to the others.
eq.
INPUT
startdate - enddate
10/24/2016 - 10/24/2016
10/26/2016 - 10/28/2016
OUTPUT
10/24/2016 - 10/24/2016 - NOT SEQUENTIAL
10/26/2016 - 10/26/2016 - SEQUENTIAL
10/27/2016 - 10/27/2016 - SEQUENTIAL
10/28/2016 - 10/28/2016 - SEQUENTIAL
For now I am playing around this solution
Check if date range is sequential in c#?
but i hope we i can find a better solution on how to properly do it.
Thank you and have a good day!
If by "sequential" we mean that the second date is the day after the first date then we can do the following:
private bool CheckSequential(DateTime date1, DateTime date2)
{
// strips off time portion
var d1 = date1.Date;
var d2 = date2.Date;
// add 1 to first date
d1 = d1.AddDays(1);
// compare them
if(DateTime.Compare(d1, d2) == 0)
return true;
else
return false;
}

How to get work week from two dates [duplicate]

This question already has answers here:
how to calculate number of weeks given 2 dates?
(7 answers)
Closed 9 years ago.
Lets say, I have two date Order date - 1/1/2014 and Delivery date - 6/2/2014. Now if I want to calculate how much work week its taken (Order date-delivery date), how can I do it in c#.
If you want the number of worked days in a date range, you can use this:
var from = DateTime.Today.AddDays(-10);
var to = DateTime.Today;
var daysOfWeek = new DayOfWeek[] { DayOfWeek.Monday, DayOfWeek.Tuesday
, DayOfWeek.Wednesday, DayOfWeek.Friday
, DayOfWeek.Thursday };
var days = Enumerable.Range(0, 1 + to.Subtract(from).Days)
.Select((n, i) => from.AddDays(i).DayOfWeek)
.Where(n => daysOfWeek.Contains(n.DayOfWeek));
If you want the number of weeks during a date range, use this:
(int)((to - from).TotalDays/7)
(int)((DeliveryDate-OrderDate).TotalDays/7)
I am presuming by "how much workweek" you mean "how many workdays". This is not so straightforward as it depends on the culture and you need to take holidays into account.
If you rely on Mon through Fri being the work days you could use a solution similar to what was discussed in c# DateTime to Add/Subtract Working Days, counting each day from Order Date to Delivery Date for which the conditions hold.
That Q&A still leaves you with the issue of how to determine the holidays of a certain region (be warned - in Switzerland each part of the country has different holidays!).
Update: From Nagaraj's suggested link I gather that you might also refer to "weeks" as chunks (that is "how many workweeks it has taken"). If so, in turn, you will need to define how many days of a week must be taken to take the week into account...
I'm using strings and convert that to dates, because I'm not sure where you get your dates and in what form. Adjust your code accordingly.
string orderDate = #"1/1/2014";
string deliveryDate = #"6/2/2014";
// This will give you a total number of days that passed between the two dates.
double daysPassed = Convert.ToDateTime(deliveryDate).
Subtract(Convert.ToDateTime(orderDate)).TotalDays;
// Use this if you want actual weeks. This will give you a double approximate. Change to it to an integer round it off (truncate it).
double weeksPassed = daysPassed / 7;
// Use this if you want to get an approximate number of work days in those weeks (based on 5 days a week schedule).
double workDaysPassed = weeksPassed * 5;
I guess you are not interested in working days but weeks. You can use GetWeekOfYear:
http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear%28v=vs.110%29.aspx
EDIT
To respond to the comment, here some code example:
int start = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(new DateTime(2014, 1, 14), System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
int end = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(new DateTime(2014, 2, 3), System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
int weeks = end - start;
That should give you the weeks needed.

use NodaTime to calculate an inclusive days period

So for example if I have the following code:
var nodaStart = new LocalDate(2012, 5, 1);
var nodaEnd = new LocalDate(2012,5,2);
var daysBetween = Period.Between(nodaStart, nodaEnd,PeriodUnits.Day);
Then daysBetween.Days == 1
However, the range I calculate needs to count that as 2 days. i.e. it needs to be inclusive of the start and end date.
The actual method can take and start and end date (that are no more than a year apart) and needs to calculate the number of days. If there are more than 31 days then the remainder are returned as a number of whole weeks.
I have that logic working fine but because the count is exclusive I'm one day out.
I guess I can just do startDate.addDays(-1) before I create nodaStart from it but I wonder if there's a more elegant / pretty way to have noda return the Period.
Thanks
UPDATE:
I've had a read of the source code for the Period class and the + operator is overloaded so I can add
daysBetween += Period.FromDays(1);
(Sorry it's taken me so long to answer this - I hadn't seen it before.)
Any of:
Adding a day to the end before calculating (this is the most logical approach, IMO - as Roger says, you want the start of the next day, effectively)
Subtracting a day from the start before calculating
Adding 1 to the number of days you get out of the end
should be fine. I don't think Noda Time will change to make this any simpler. Between is a sort of "fuzzy around units" version of a subtraction operator - and you won't find many subtraction operators where 2 - 1 is 2.
For "fuzzy" brained humans, we may consider a period of days to be inclusive of start and end date if it identifies a single day, week, month, etc (cf. whole multiple of), so you could code it:
var start = new NodaTime.LocalDateTime(s.Year, s.Month, s.Day, s.Hour, s.Minute);
var end = new NodaTime.LocalDateTime(e.Year, e.Month, e.Day, e.Hour, e.Minute);
NodaTime.Period periodInclusive = NodaTime.Period.Between(start, end.PlusDays(1), NodaTime.PeriodUnits.AllDateUnits);
NodaTime.Period period = NodaTime.Period.Between(start, end, NodaTime.PeriodUnits.AllDateUnits);
bool isInclusivePeriod = periodInclusive.Days + periodInclusive.Weeks + periodInclusive.Months + periodInclusive.Years <
period.Days + period.Weeks + period.Months + period.Years;
period = isInclusivePeriod ? periodInclusive : period;
// do stuff with period here....

calculate period between two monthcalender in C#

I have two monthcalender in C# win application , and I need to calculate the period between then.
I need how many day between two or three month or also years
I need how many month between tow different years.
When I use :
monthcalender.selectstart.month;
this command just calculate the different between months in same year, but when move to next year the value be negative.
and same for days, I use :
monthcalender.selectstart.dayofyear;
monthcalendar.SelectionStart is a DateTime structure, which you can do calculations with. Subtracting two dates will result in a TimeSpan structure, which has various properties that should be of use to you.
TimeSpan timeBetween = calendar1.SelectionStart - calendar2.SelectionStart;
MessageBox.Show("Days between dates: " + timeBetween.TotalDays);
If you wanted to use the Month property of the DateTime, you could do something like:
DateTime d1 = calendar1.SelectionStart;
DateTime d2 = calendar2.SelectionStart;
ints monthsBetween = d1.Month + d1.Year * 12 - d2.Month - d2.Year * 12;
That would leave the days of the month out of the equation though.

Categories

Resources