How to calculate Birthday to Age [duplicate] - c#

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.

Related

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

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.

Age in years with decimal precision given a datetime

How can I get the age of someone given the date of birth in a C# datetime.
I want a precise age like 40.69 years old
This will calculate the exact age. The fractional part of the age is calculated relative to the number of days between the last and the next birthday, so it will handle leap years correctly.
The fractional part is linear across the year (and doesn't take into account the different lengths of the months), which seems to make most sense if you want to express a fractional age.
// birth date
DateTime birthDate = new DateTime(1968, 07, 14);
// get current date (don't call DateTime.Today repeatedly, as it changes)
DateTime today = DateTime.Today;
// get the last birthday
int years = today.Year - birthDate.Year;
DateTime last = birthDate.AddYears(years);
if (last > today) {
last = last.AddYears(-1);
years--;
}
// get the next birthday
DateTime next = last.AddYears(1);
// calculate the number of days between them
double yearDays = (next - last).Days;
// calcluate the number of days since last birthday
double days = (today - last).Days;
// calculate exaxt age
double exactAge = (double)years + (days / yearDays);
This would be an approximative calculation:
TimeSpan span = DateTime.Today.Subtract(birthDate);
Console.WriteLine( "Age: " + (span.TotalDays / 365.25).toString() );
BTW: see also this question on Stack Overflow: How do I calculate someone’s age in C#?
An approximite would be:
DateTime bd = new DateTime(1999, 1, 2);
TimeSpan age = DateTime.Now.Subtract(bd);
Console.WriteLine(age.TotalDays / 365.25);
The 40 years part is easy enough. But to get a truly accurate decimal point, I'm not sure how you translate the rest of the age into a decimal number. You see age is expressed in Years, Months, Days, Hours, Seconds. And the calculation isn't that easy. You have to deal with anniversary dates. Like if someone was born on January 31st, when are they 1 month old? The answer is March 1st. But in some years that is 28 days later and some years 29 days later. Here is a javascript implementation I did that tries to deal with this.
But I suppose the decimal could express the number of days since the most recent birthday anniversay divided by the number of days till the next birthday anniversary. And if you wanted to get more precise you could do it in seconds using the same principle.
But I think it is a poor representation of an age. We just don't usually represent an age like that.
And make sure your datetimes are in the same timezone for your comparisons.
You could do this:
Console.WriteLine(DateTime.Now.Date.Subtract(new DateTime(1980, 8, 1)).TotalDays / 365.25);
how much error is allowed in the fractional portion? a precise age would be
31 years, 10 days, 3 hours, etc. depending on the precision wanted.

Age in years from DateTime (Date of birth) [duplicate]

This question already has answers here:
Closed 13 years ago.
Duplicate
How Can I calculate Someone's Age in C#?
I have a datetime variable that represents the date of birth of a user.
How can I get the age in years from this?
Update
I want a precise birthday, so 30.45 years or something.
Try the following (assuming the date of birth is stored in dtDOB):
public int getAgeInYears {
TimeSpan tsAge = DateTime.Now.Subtract(dtDOB);
return new DateTime(tsAge.Ticks).Year - 1;
}
Stolen from the answer to Jeff's question:
DateTime now = DateTime.Now;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;
You can try with (in Vb):
Dim dateOfBirth As Date
Now.Subtract(dateOfBirth).TotalDays \ 365
\ is an Integer division in Vb, I do not know if it has a correspondant in C#.

Exact age calculation [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I calculate someone's age in C#?
Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, isn't it better to calculate the exact age?
Maybe
DateTime dt1 = DateTime.Now;
TimeSpan dt2;
dt2 = dt1.Subtract(new DateTime(1975, 12, 01));
double year = dt2.TotalDays / 365;
The result of year is 32.77405678074
Could this code be OK?
Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, doesn't it better to calculate the exact age?
My guess would be that this is a localization issue, though I don't know how it would happen, since (at least for me) the profile has you fill out your age in the format "YYYY/MM/DD". But your birthday is one that reads as a valid date (January 12th) in traditional U.S. settings, so this is the area I'd look into. I was born in 1975, also, and my birthday is next month, and it's got my age right.
If you were born on January 12th 1975, you would be 33 years old today.
If you were born on December 1st 1975, you would be 32 years old today.
If you read the note by the birthday field when editing your profile you'll see it says "YYYY/MM/DD", I'm sure it will try to interpret dates of other formats but it looks like it interprets MM/DD/YYYY (US standard dates) in preference to DD/MM/YYYY (European standard dates). The easy fix is to enter the date of your birthday according to the suggested input style.
Actually, because of leap years, your code would be off. Since the timespan object has no TotalYears property the best way to get it would be this
Pardon the VB.Net
Dim myAge AS Integer = DateTime.Now.year - BirthDate.year
If Birthdate.month < DateTime.Now.Month _
OrElse BirthDate.Month = DateTime.Now.Month AndAlso Birthdate.Day < DateTime.Now.Day Then
MyAge -= 1
END IF
int ag1;
string st, ag;
void agecal()
{
st = TextBox4.Text;
DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
dtfi.ShortDatePattern = "MM/dd/yyyy";
dtfi.DateSeparator = "/";
DateTime dt = Convert.ToDateTime(st, dtfi);
ag1 = int.Parse(dt.Year.ToString());
int years = DateTime.Now.Year - ag1;
ag = years.ToString();
TextBox3.Text = ag.ToString();
}

Categories

Resources