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

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();
}

Related

Writing out how many years and months are in a date range (i.e. 2 years and 3 months) [duplicate]

This question already has answers here:
How to get difference between two dates in Year/Month/Week/Day?
(23 answers)
Closed 6 years ago.
In the case of 2/1/2016 - 1/31/2019:
I would like to output: '3 years' since the date range is 3 years.
In the case of 2/1/2016 - 3/31/2019:
I would like to output: '3 years and 2 months' since the date range is 3 years and 2 months.
I don't need to worry about days so I can just round up if that is the norm.
Are there any c# helpers out there that can help me with something like this?
For approximately calculating years and months, you can do the following :
DateTime dayStart;
DateTime dateEnd;
TimeSpan ts = dateEnt - dateStart
int years = ts.Days / 365;
int months = (ts.Days % 365) / 31;
For exact calulations , it can be tricky considering the leap years, different number of days in months,etc.
You could use this which doesn't really care about leap years:
DateTime first = new DateTime(2016, 2, 1);
DateTime second = new DateTime(2019, 3, 31);
double totalMonths = (second - first).TotalDays / (365.25 / 12);
int years = (int)totalMonths / 12;
int months = (int)Math.Round(totalMonths - (years * 12), 0);

How to calculate Birthday to Age [duplicate]

This question already has answers here:
How do I calculate someone's age based on a DateTime type birthday?
(74 answers)
Closed 7 years ago.
string birthDay = "";
_birthDay = DateTime.Parse(this.BirthDay.Value.ToString()).ToString("yyyyMMdd");
DateTime today = DateTime.Today;
int age = today.Year - _birthDay.Year;
if (_birthDay > today.AddYears(-age)) age--;
txtbox1.Text = age;
It seems error, How to calculate age from birth day?
int age = (DateTime.Today - _birthDay ).TotalDays;
if you want the difference in years you can refer this thread
TimeSpan span = DateTime.Today - _birthDay;
// because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int age = (zeroTime + span).Year - 1;
If you want to calculate it very precision try below:
The most important thing is How many days left since you born.
the 2nd important things is how many years left since you born.
But...not every year is 365 days always.you have to consider the condition about leap year.
give you a clue:if your age is 25,assume every year is 365 days,so the days left is 365*25+x(1<=x<=365)..etc..
see:
Calculate age in C#
But you have to ask yourself about the necessary precision since timezones will affect this. In very rare cases there will some ambiguity. For example, If it's your birthday and you commit a crime when you're 17 in one timezone but 18 in another there's going to be an issue. If the answer is critical then you will need to provide some sort of message back to your user to explain some of the vagaries of computing age.

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

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...

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);
}

What is the number of days between two dates? [duplicate]

This question already has answers here:
Calculate difference between two dates (number of days)?
(17 answers)
Closed 9 years ago.
We want to find the number of days between two dates. This is simple when the dates are in the same year.
Is there a built-in way to do this if the dates are in different years, or do we just have to loop through each year?
Subtracting a date from another yields a TimeSpan. You can use this to determine the number of whole days using the Days property, or whole and fractional days using the TotalDays property.
DateTime start = ...;
DateTime end = ...;
int wholeDays = (end - start).Days;
or
double totalAndPartialDays = (end - start).TotalDays;
you can probably do something like:
TimeSpan ts = endDate - startDate;
ts.Days
What are you missing?
DateTime - DateTime => Timespan
and Timespan has Days and TotalDays properties.
DateTime date1 = DateTime.Now;
DateTime date2 = new DateTime(date1.Year - 2, date1.Month, date1.Day);
Int32 difference = date1.Subtract(date2).Days;

Categories

Resources