calculate period between two monthcalender in C# - 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.

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

Number of days for a given year inside a date range

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.

How to get Difference hours Between two date

I want get diffrences Day,Hour and Day between two days.
I use belowe Code :
DateTime LastDate = DateTime.Parse("2/12/2015 11:24:23 AM");
int differenceDay = DateTime.Now.Subtract(LastDate).Days;
int differenceHoure = DateTime.Now.Hour - LastDate.Hour;//returns -11
int differenceMinute = DateTime.Now.Minute - LastDate.Minute;
When I want get Hours its return mines (-11 e.t).
How can I get positive Diffrence Hour ?
anyone can you help me?
I want get Last Dat and show its by string how days afterd now.
You're subtracting component-wise (i.e. "this hour-of-day minus that hour-of-day, this minute-of-hour minus that minute-of-hour"). Don't do that - it won't work if the current hour-of-day is earlier than the hour-of-day of lastDate, or the same for minute-of-hour - you get a negative value, exactly as you've seen.
Instead, subtract one DateTime from another to get a TimeSpan and use that single TimeSpan for all the components:
DateTime lastDate = DateTime.Parse("2/12/2015 11:24:23 AM");
TimeSpan difference = DateTime.Now - lastDate;
int days = difference.Days;
int hours = difference.Hours;
int minutes = difference.Minutes;
That will still be negative if lastDate is after DateTime.Now, of course.
Note that this will give you a result which is meaningful if you display all three components. For example, it might give you "2 days, 3 hours and 10 minutes". If instead you want to represent the same TimeSpan as "2.194 days" or "51.166 hours" or "3160 minutes" then you can use TotalDays, TotalHours and TotalMinutes.
If you always want a positive TimeSpan - the equivalent of Math.Abs but for TimeSpan you can just use TimeSpan.Duration():
TimeSpan difference = (DateTime.Now - lastDate).Duration();

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.

In C#, parse out biweekly sets of dates from a collection of dates?

I recently asked this question, to take a list of datetime objects and parse out:
Weekly Recurrence: Collections of dates that match the same dayOfWeek, hour, minute to get a set of lists where each item in the list matches that Key where:
Key is concatenation of DayOfWeek + hour + minute
Monthly Recurrence: Collections of dates that match the same weekOfMonth, dayOfWeek, hour, minute to get a set of lists where each item in the list matches that Key where:
Key is concatenation of WeekOfMonth + DayOfWeek + hour + minute
both of these are working great.
I have an additional requirement now that I am struggling with to support bi weekly recurrence (every other week). I am trying to figure out the right key to match on that would work as both the other use cases above have logical computed key but can't figure the algorith / key for every other week
You'll need to figure out the week number for the date in question.
For example:
var dt = new DateTime(...); // your datetime
var cal = new System.Globalization.GregorianCalendar();
var weekNum = cal.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
There are different strategies for counting weeks of the year, which you specify with a CalendarWeekRule and corresponding DayOfWeek for the starting day of the week. You can read more here.
Once you have a week number, you can do some math to make it "bi-weekly":
int biweeklyKey = weekNum % 2;
The value will be either 0 or 1, which you can use as a key in your algorithm.

Categories

Resources