How to get duration between start and end date [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Converting Days into Human Readable Duration Text
How do I calculate difference in years and months given a start and end
I use (end date - start date).TotalDays it returns total days. For example, 145 days
But I don't want total days.
It is possible to convert 145 days to 3 months and 25 days something like this.

A bit harder than it initially seems...
I suppose you could do something like this, which has the advantage of counting actual calendar months rather than estimating months to be 30days or similar.
var now = DateTime.Now;
var future = DateTime.Now.AddDays(new Random().NextDouble() * 365);
//dates above for example only
var xx = Enumerable.Range(0,int.MaxValue)
.Select(i => new{numMonths = i, date = now.AddMonths(i)})
.TakeWhile(x => x.date < future)
.Last();
var remainingDays = (future - xx.date).TotalDays;
Console.WriteLine("{0} months and {1} days",xx.numMonths,remainingDays);

if you assume a month to be 30 days, this below might help.
var start = DateTime.Today;
var end = DateTime.Today.AddDays(99);
var timeSpan = end.Subtract(start);
var months = (int)timeSpan.TotalDays / 30;
var days = timeSpan.TotalDays % 30;
var str = string.Format("{0} months, {1} days", months, days);

The difference of two DateTime objects results in a TimeSpan object. Since the time spanned by a month is not consistent among months, how would a TimeSpan object be represented by a number of months?
In order to calculate the number of months between two dates, you'd need to know the start date and end date ahead of time so you can calculate the actual number of months (keeping in mind leap years, etc.) between them.

If you want years, months, days:
Years = max number of years you can subtract from end date such that the result is still > start date.
Months = max number of months you can subtract from the previous result such that the result is still > start date.
Days = number of days between previous result and start date.

To overcome the number of days problem in a month, just look at the years and months
DateTime d1 = New DateTime(2002, 1, 1);
DateTime d2 = New DateTime(2000, 10, 1);
int years = Math.Abs((d1.Year - d2.Year));
int months = ((years * 12) + Math.Abs((d1.Month - d2.Month)));

Try use the time span to string...

Related

C# - Get the first day and last day of the week knowing the week number, month number and year

so the problem is this: I managed to get the number of weeks that make up a month (for example: May 2022 is made up of 6 weeks counting from day 1 to day 31 without exception). So having the number of weeks that make up a month I need to know, knowing also the number of the month and the year, which will be the first and last day of the selected week.
I tried to do some research but I only find solutions that use the Calendar.GetWeekOfYear method but, as I said before, I have the week number for the single month not the total for the year.
I hope you can help me. Thanks in advance.
If I understood correctly it should look something like this
var week = 2;
var month = 5;
var year = 2022;
var firstDayOfMonth = new DateTime(year, month, 1);
var dayOfWeek = firstDayOfMonth.DayOfWeek;
var diffToMonday = (7 + (dayOfWeek - DayOfWeek.Monday)) % 7;
var firstMonday = firstDayOfMonth.AddDays(-diffToMonday);
var requestedMonday = firstMonday.AddDays(7 * (week - 1));
var requestedSunday = firstMonday.AddDays(7 * week - 1);

Calculate Year, Month and Day between two Dates in C# [duplicate]

This question already has answers here:
Calculate Years, Months, weeks and Days
(11 answers)
Closed 6 years ago.
I want exact Year, Month and Day elapsed between two dates.
DateTime startDate = new DateTime(1974, 8, 15);
DateTime endDate = DateTime.Now.ToLocalTime();
I wish to find Number of Years, Months and Days elapsed between the above two days using C#?
My Expected Output
Years: 68 Months: 10 Days: 23
I referred one of the post, in that they explained about only days Calculate difference between two dates (number of days)?
But I need all three - Year, Month and Day. Kindly assist me how to calculate...
Explanation for Duplicate:
Already a question with same logic posted in Calculate Years, Months, weeks and Days, the answer provided in that question is too lengthy and in my question I asked only Year, Month and Date not Week. The Concept is same but the logic is different for calculating days comparing to that question, Here I got the answer in a very simplified manner. I satisfied in my answer.
Exact Duplicate:
Original Question: How to get difference between two dates in Year/Month/Week/Day? (Asked 7 Years ago)
Your Marked Question: Calculate Years, Months, weeks and Days (Asked 5 Years ago)
Interesting Question:
The Solution is
void Main()
{
DateTime zeroTime = new DateTime(1, 1, 1);
DateTime olddate = new DateTime(1947, 8,15);
olddate.Dump();
DateTime curdate = DateTime.Now.ToLocalTime();
curdate.Dump();
TimeSpan span = curdate - olddate;
// because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;
int months = (zeroTime + span).Month - 1;
int days = (zeroTime + span).Day;
years.Dump();
months.Dump();
days.Dump();
}

Nodatime calculation of years/months/days in X days

Say I have 678 days, how to calculate how many years, months and days are there from that moment?
Duration duration = Duration.FromStandardDays(678);
Instant now = SystemClock.Instance.Now;
Instant future = now + duration;
// I have to convert NodaTime.Instant to NodaTime.LocalDate but don't know how
Period period = Period.Between(now, future);
Console.WriteLine("{0} years, {1} months, {2} days", period.Years, period.Months, period.Days);
You can indeed do this with Noda Time.
First, you need a starting point. This uses the current day in the local time zone. You may wish to use a different day, or a different time zone, depending on your scenario.
Instant now = SystemClock.Instance.Now;
DateTimeZone timeZone = DateTimeZoneProviders.Bcl.GetSystemDefault();
LocalDate today = now.InZone(timeZone).Date;
Then just add the number of days:
int days = 678;
LocalDate future = today.PlusDays(days);
Then you can obtain a period with the units desired:
Period period = Period.Between(today, future, PeriodUnits.YearMonthDay);
Console.WriteLine("{0} years, {1} months, {2} days",
period.Years, period.Months, period.Days);
It's important to recognize that the result represents "time from now". Or if you substitute a different starting point, it's "time from (the starting point)". Under no circumstances should you just think that the result is X days = Y years + M months + D days. That would be nonsensical, since the number of days in a year and the number of days in a month depend on which year and month you're talking about.
You just need to add the number of days to the current time:
var now = DateTime.Now;
var future = now.AddDays(678);
int years = future.Year - now.Year;
int months = future.Month - now.Month;
if (months < 0)
{
years--;
months += 12;
}
int days = future.Day + DateTime.DaysInMonth(now.Year, now.Month) - now.Day;

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.

Get Date Range by week number c# [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
In .net, knowing the week number how can I get the weekdays date?
Hello,
I've got a question for ya'll.
How do i get the date range of a given week number.
For example:
If I enter week 12 the output should be:
21-03-2011
22-03-2011
23-03-2011
24-03-2011
25-03-2011
26-03-2011
27-03-2011
I really hope you guys can help me out, i just cant find the awnser anywhere!
Thanks in advance.
Note
I appear to have missed bug. The current code have been updated as of 2012-01-30 to account for this fact and we now derive the daysOffset based on Tuesday which according to Mikael Svenson appears to solve the problem.
These ISO8601 week date calculations are a bit wonky, but this is how you do it:
DateTime jan1 = new DateTime(yyyy, 1, 1);
int daysOffset = DayOfWeek.Tuesday - jan1.DayOfWeek;
DateTime firstMonday = jan1.AddDays(daysOffset);
var cal = CultureInfo.CurrentCulture.Calendar;
int firstWeek = cal.GetWeekOfYear(jan1, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
var weekNum = ww;
if (firstWeek <= 1)
{
weekNum -= 1;
}
var result = firstMonday.AddDays(weekNum * 7 + d - 1);
return result;
Basically calculate a reference point, then add days, the hard stuff has to do with the fact that week 53 can sometimes occur in January and week 1 can sometimes occur in December. You need to adjust for that and this is one way to do that.
The above code calculates the date off a year (yyyy) and week number (ww) and day of week (d).
Find out which day of the week was the first January of the year (e.g. in 2011 it was Saturday)
Add the necessary count of days to become the next monday (2 days)
From this day on, add (Number of weeks - 1) * 7 days to get the first day of the week you are interested in
-Display this day plus the next days to get the whole week
Something like this should do the trick
DateTime d = new DateTime(someYear, 1, 1);
d.AddDays(numWeeks * 7);
for (int x = 0; x < 7; x++)
{
Console.WriteLine(d.ToShortDateString());
d.AddDays(1);
}

Categories

Resources