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

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

Related

Trying to figure out current age based on birthday and current date down to the day [duplicate]

This question already has answers here:
How do I calculate someone's age based on a DateTime type birthday?
(74 answers)
Closed 2 years ago.
I am designing a practice visual c# program that has you pick your birth date from a dateTimePicker and comparing it to the current date to display in a textBox what your current age is.
I would like to factor in which day of the month you picked to refine the age result rather than just assuming you're a certain age because you were born in that particular month.
This is what I have so far:
public void button1_Click(object sender, EventArgs e)
{
var birthdayYear = dateTimePicker1.Value.Year;
var birthdayMonth = dateTimePicker1.Value.Month;
var birthdayDay = dateTimePicker1.Value.Day;
var currentYear = DateTime.Now.Year;
var currentMonth = DateTime.Now.Month;
var currentDay = DateTime.Now.Day;
int currentAge = DateTime.Now.Year - dateTimePicker1.Value.Year;
if (birthdayMonth >= currentMonth)
{
currentAge--;
}
string currentResult = Convert.ToString(currentAge);
ageResult.Text = currentResult;
}
Do not try to implement date math yourself. Date math is notoriously difficult to get right and has a fair share of tricky edge cases.

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.

DateTime difference from current date to figure out a past date [duplicate]

This question already has answers here:
How to subtract one year from DateTime [closed]
(4 answers)
Closed 8 years ago.
I am trying to find a date (string) that is 5 years from current date in the past:-
DateTime.UtcNow.Date - DateString = 5 years
Can anyone help me formulate this into c# syntax?
var myDate = DateTime.UtcNow;
var newDate = myDate.AddYears(-5);
You can add or subtract a TimeSpan from a DateTime object to get another DateTime object.
var fiveYearsAgo = DateTime.Now - TimeSpan.FromYears(5);
var fiveYearsFromNow = DateTime.Now + TimeSpan.FromYears(5);

C# Get Month INT from Month String [duplicate]

This question already has answers here:
How to parse a month name (string) to an integer for comparison in C#?
(15 answers)
Closed 6 years ago.
I found a lot of ways to get the name from a number but now I need it the other way around.
If the string equals April, I want to convert it to int "4".
Does anyone know the best way to accomplish this server side?
int month = DateTime.ParseExact(MonthNameStr, "MMMM", CultureInfo.CurrentCulture ).Month
or you can do
int month = DateTimeFormatInfo.CurrentInfo.MonthNames.ToList().IndexOf(MonthNameStr) + 1;
int month = DateTime.ParseExact("April", "MMMM", CultureInfo.InvariantCulture).Month;
You can use the DateTime.ParseExact Method with a custom format specifier consisting only of the the "MMMM" Custom Format Specifier:
int month = DateTime.ParseExact("April", "MMMM", new CultureInfo("en-US"))
.Month;

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